Source code changes.

* Changed newlines to \n.
* Removed whitespace before colons.
* Fixed several alignments.
This commit is contained in:
Stefan Schindler 2014-09-30 16:07:25 +02:00
parent b27cbd5036
commit f24ca9a840
268 changed files with 40227 additions and 40227 deletions

View file

@ -1,306 +1,306 @@
cmake_minimum_required(VERSION 2.8)
# define a macro that helps defining an option
macro(sfml_set_option var default type docstring)
if(NOT DEFINED ${var})
set(${var} ${default})
endif()
set(${var} ${${var}} CACHE ${type} ${docstring} FORCE)
endmacro()
# set a default build type if none was provided
# this has to be done before the project() instruction!
sfml_set_option(CMAKE_BUILD_TYPE Release STRING "Choose the type of build (Debug or Release)")
# project name
project(SFML)
# include the configuration file
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/Config.cmake)
# setup version numbers
set(VERSION_MAJOR 2)
set(VERSION_MINOR 1)
set(VERSION_PATCH 0)
# add the SFML header path
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
# add an option for choosing the build type (shared or static)
if(NOT (SFML_OS_IOS OR SFML_OS_ANDROID))
sfml_set_option(BUILD_SHARED_LIBS TRUE BOOL "TRUE to build SFML as shared libraries, FALSE to build it as static libraries")
else()
if(SFML_OS_IOS)
set(BUILD_SHARED_LIBS FALSE)
elseif(SFML_OS_ANDROID)
set(BUILD_SHARED_LIBS TRUE)
endif()
endif()
# add an option for building the examples
if(NOT (SFML_OS_IOS OR SFML_OS_ANDROID))
sfml_set_option(SFML_BUILD_EXAMPLES FALSE BOOL "TRUE to build the SFML examples, FALSE to ignore them")
else()
set(SFML_BUILD_EXAMPLES FALSE)
endif()
# add an option for building the API documentation
sfml_set_option(SFML_BUILD_DOC FALSE BOOL "TRUE to generate the API documentation, FALSE to ignore it")
# add an option for choosing the OpenGL implementation
sfml_set_option(SFML_OPENGL_ES ${OPENGL_ES} BOOL "TRUE to use an OpenGL ES implementation, FALSE to use a desktop OpenGL implementation")
# Mac OS X specific options
if(SFML_OS_MACOSX)
# add an option to build frameworks instead of dylibs (release only)
sfml_set_option(SFML_BUILD_FRAMEWORKS FALSE BOOL "TRUE to build SFML as frameworks libraries (release only), FALSE to build according to BUILD_SHARED_LIBS")
# add an option to let the user specify a custom directory for frameworks installation (SFML, sndfile, ...)
sfml_set_option(CMAKE_INSTALL_FRAMEWORK_PREFIX "/Library/Frameworks" STRING "Frameworks installation directory")
# add an option to automatically install Xcode templates
sfml_set_option(SFML_INSTALL_XCODE_TEMPLATES FALSE BOOL "TRUE to automatically install the Xcode templates, FALSE to do nothing about it. The templates are compatible with Xcode 4 and 5.")
endif()
# Android options
if(SFML_OS_ANDROID)
# force usage of the STL port
set(ANDROID_USE_STLPORT TRUE)
# make sure there's the android library available
if (${ANDROID_NATIVE_API_LEVEL} LESS 9)
message(FATAL_ERROR "API level must be equal or greater than 9")
endif()
# install everything in $NDK/sources/ because this path is appended by the NDK (convenient)
set(CMAKE_INSTALL_PREFIX ${ANDROID_NDK}/sources/sfml)
# we install libs in a subdirectory named after the ABI (lib/mips/*.so)
set(LIB_SUFFIX "/${ANDROID_ABI}")
# this is a workaround to compile sfml-activity without stlport_shared as dependency
# we save the original compilation command line to restore it later in Macro.cmake
set(CMAKE_CXX_CREATE_SHARED_LIBRARY_WITH_STLPORT ${CMAKE_CXX_CREATE_SHARED_LIBRARY})
set(CMAKE_CXX_CREATE_SHARED_LIBRARY_WITHOUT_STLPORT "<CMAKE_CXX_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <SONAME_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>")
endif()
# define SFML_STATIC if the build type is not set to 'shared'
if(NOT BUILD_SHARED_LIBS)
add_definitions(-DSFML_STATIC)
endif()
# remove SL security warnings with Visual C++
if(SFML_COMPILER_MSVC)
add_definitions(-D_CRT_SECURE_NO_DEPRECATE)
endif()
# define SFML_OPENGL_ES if needed
if(SFML_OPENGL_ES)
add_definitions(-DSFML_OPENGL_ES)
add_definitions(-DGL_GLEXT_PROTOTYPES)
endif()
# define an option for choosing between static and dynamic C runtime (Windows only)
if(SFML_OS_WINDOWS)
sfml_set_option(SFML_USE_STATIC_STD_LIBS FALSE BOOL "TRUE to statically link to the standard libraries, FALSE to use them as DLLs")
# the following combination of flags is not valid
if (BUILD_SHARED_LIBS AND SFML_USE_STATIC_STD_LIBS)
message(FATAL_ERROR "BUILD_SHARED_LIBS and SFML_USE_STATIC_STD_LIBS cannot be used together")
endif()
# for VC++, we can apply it globally by modifying the compiler flags
if(SFML_COMPILER_MSVC AND SFML_USE_STATIC_STD_LIBS)
foreach(flag
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
if(${flag} MATCHES "/MD")
string(REGEX REPLACE "/MD" "/MT" ${flag} "${${flag}}")
endif()
endforeach()
endif()
endif()
# setup Mac OS X stuff
if(SFML_OS_MACOSX)
# SFML_BUILD_FRAMEWORKS needs two things :
# first, it's available only for release
# (because cmake currently doesn't allow specifying a custom framework name so XXX-d is not possible)
# secondly, it works only with BUILD_SHARED_LIBS enabled
if(SFML_BUILD_FRAMEWORKS)
# requirement #1
if(NOT CMAKE_BUILD_TYPE STREQUAL "Release")
message(FATAL_ERROR "CMAKE_BUILD_TYPE should be \"Release\" when SFML_BUILD_FRAMEWORKS is TRUE")
return()
endif()
# requirement #2
if(NOT BUILD_SHARED_LIBS)
message(FATAL_ERROR "BUILD_SHARED_LIBS should be TRUE when SFML_BUILD_FRAMEWORKS is TRUE")
return()
endif()
endif()
# configure Xcode templates
if(CMAKE_OSX_ARCHITECTURES)
# maybe multiple arches are present in CMAKE_OSX_ARCHITECTURES
# we simply need to replace ';' by ' ' (space) and store the result in XCODE_TEMPLATES_ARCH
string(REPLACE ";" " " XCODE_TEMPLATES_ARCH "${CMAKE_OSX_ARCHITECTURES}")
else()
# no arch was provided to cmake, so we use the default one
set(XCODE_TEMPLATES_ARCH "\$(NATIVE_ARCH_ACTUAL)")
endif()
endif()
if(SFML_OS_LINUX OR SFML_OS_FREEBSD)
set(PKGCONFIG_DIR lib${LIB_SUFFIX}/pkgconfig)
if(SFML_OS_FREEBSD)
set(PKGCONFIG_DIR libdata/pkgconfig)
endif()
if(BUILD_SHARED_LIBS)
sfml_set_option(SFML_INSTALL_PKGCONFIG_FILES FALSE BOOL "TRUE to automatically install pkg-config files so other projects can find SFML")
if(SFML_INSTALL_PKGCONFIG_FILES)
foreach(sfml_module IN ITEMS all system window graphics audio network)
CONFIGURE_FILE(
"tools/pkg-config/sfml-${sfml_module}.pc.in"
"tools/pkg-config/sfml-${sfml_module}.pc"
@ONLY)
INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/tools/pkg-config/sfml-${sfml_module}.pc"
DESTINATION "${CMAKE_INSTALL_PREFIX}/${PKGCONFIG_DIR}")
endforeach()
endif()
else()
if(SFML_INSTALL_PKGCONFIG_FILES)
message(WARNING "No pkg-config files are provided for the static SFML libraries (SFML_INSTALL_PKGCONFIG_FILES will be ignored).")
endif()
endif()
endif()
# enable project folders
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER "CMake")
# add the subdirectories
add_subdirectory(src/SFML)
if(SFML_BUILD_EXAMPLES)
add_subdirectory(examples)
endif()
if(SFML_BUILD_DOC)
add_subdirectory(doc)
endif()
# setup the install rules
if(NOT SFML_BUILD_FRAMEWORKS)
install(DIRECTORY include
DESTINATION .
COMPONENT devel
FILES_MATCHING PATTERN "*.hpp" PATTERN "*.inl")
else()
# find only "root" headers
file(GLOB SFML_HEADERS RELATIVE ${PROJECT_SOURCE_DIR} "include/SFML/*")
# in fact we have to fool cmake to copy all the headers in subdirectories
# to do that we have to add the "root" headers to the PUBLIC_HEADER
# then we can run a post script to copy the remaining headers
# we need a dummy file in order to compile the framework
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp
COMMAND touch ${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp)
set(SFML_SOURCES ${SFML_HEADERS})
list(APPEND SFML_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp)
# create SFML.framework
add_library(SFML ${SFML_SOURCES})
# edit target properties
set_target_properties(SFML PROPERTIES
FRAMEWORK TRUE
FRAMEWORK_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
MACOSX_FRAMEWORK_IDENTIFIER org.sfml-dev.SFML
MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
MACOSX_FRAMEWORK_BUNDLE_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
PUBLIC_HEADER "${SFML_HEADERS}")
# add the remaining headers
add_custom_command(TARGET SFML
POST_BUILD
COMMAND cp -r ${PROJECT_SOURCE_DIR}/include/SFML/* $<TARGET_FILE_DIR:SFML>/Headers)
# adapt install directory to allow distributing dylibs/frameworks in users frameworks/application bundle
# NOTE : it's not required to link agains SFML.framework
set_target_properties(SFML PROPERTIES
BUILD_WITH_INSTALL_RPATH 1
INSTALL_NAME_DIR "@executable_path/../Frameworks")
# install rule
install(TARGETS SFML
FRAMEWORK DESTINATION ${CMAKE_INSTALL_FRAMEWORK_PREFIX}
COMPONENT devel)
endif()
install(FILES license.txt DESTINATION ${INSTALL_MISC_DIR})
install(FILES readme.txt DESTINATION ${INSTALL_MISC_DIR})
if(NOT SFML_OS_ANDROID)
install(FILES cmake/Modules/FindSFML.cmake DESTINATION ${INSTALL_MISC_DIR}/cmake/Modules)
endif()
# install 3rd-party libraries and tools
if(SFML_OS_WINDOWS)
# install the binaries of SFML dependencies
if(ARCH_32BITS)
install(DIRECTORY extlibs/bin/x86/ DESTINATION bin)
if(SFML_COMPILER_MSVC)
install(DIRECTORY extlibs/libs-msvc/x86/ DESTINATION lib)
else()
install(DIRECTORY extlibs/libs-mingw/x86/ DESTINATION lib)
endif()
elseif(ARCH_64BITS)
install(DIRECTORY extlibs/bin/x64/ DESTINATION bin)
if(SFML_COMPILER_MSVC)
install(DIRECTORY extlibs/libs-msvc/x64/ DESTINATION lib)
else()
install(DIRECTORY extlibs/libs-mingw/x64/ DESTINATION lib)
endif()
endif()
elseif(SFML_OS_MACOSX)
# install the non-standard frameworks SFML depends on
install(DIRECTORY extlibs/libs-osx/Frameworks/sndfile.framework DESTINATION ${CMAKE_INSTALL_FRAMEWORK_PREFIX})
install(DIRECTORY extlibs/libs-osx/Frameworks/freetype.framework DESTINATION ${CMAKE_INSTALL_FRAMEWORK_PREFIX})
# install the Xcode templates if requested
if(SFML_INSTALL_XCODE_TEMPLATES)
configure_file(
"tools/xcode/templates/SFML/SFML Compiler.xctemplate/TemplateInfo.plist.in"
"${CMAKE_CURRENT_BINARY_DIR}/tools/xcode/templates/SFML/SFML Compiler.xctemplate/TemplateInfo.plist"
@ONLY)
install(DIRECTORY "tools/xcode/templates/SFML" "${CMAKE_CURRENT_BINARY_DIR}/tools/xcode/templates/SFML"
DESTINATION /Library/Developer/Xcode/Templates
PATTERN "*.in" EXCLUDE)
endif()
elseif(SFML_OS_IOS)
# fix CMake install rules broken for iOS (see http://public.kitware.com/Bug/view.php?id=12506)
if(SFML_OS_IOS)
install(DIRECTORY "${CMAKE_BINARY_DIR}/lib/\$ENV{CONFIGURATION}/" DESTINATION lib${LIB_SUFFIX})
endif()
# since the iOS libraries are built as static, we must install the SFML dependencies
# too so that the end user can easily link them to its final application
install(FILES extlibs/libs-ios/libfreetype.a extlibs/libs-ios/libjpeg.a DESTINATION lib)
elseif(SFML_OS_ANDROID)
# install extlibs
install(DIRECTORY extlibs/libs-android/${ANDROID_ABI} DESTINATION extlibs/lib)
install(FILES extlibs/Android.mk DESTINATION extlibs)
# install Android.mk so the NDK knows how to set up SFML
install(FILES src/SFML/Android.mk DESTINATION .)
endif()
cmake_minimum_required(VERSION 2.8)
# define a macro that helps defining an option
macro(sfml_set_option var default type docstring)
if(NOT DEFINED ${var})
set(${var} ${default})
endif()
set(${var} ${${var}} CACHE ${type} ${docstring} FORCE)
endmacro()
# set a default build type if none was provided
# this has to be done before the project() instruction!
sfml_set_option(CMAKE_BUILD_TYPE Release STRING "Choose the type of build (Debug or Release)")
# project name
project(SFML)
# include the configuration file
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/Config.cmake)
# setup version numbers
set(VERSION_MAJOR 2)
set(VERSION_MINOR 1)
set(VERSION_PATCH 0)
# add the SFML header path
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
# add an option for choosing the build type (shared or static)
if(NOT (SFML_OS_IOS OR SFML_OS_ANDROID))
sfml_set_option(BUILD_SHARED_LIBS TRUE BOOL "TRUE to build SFML as shared libraries, FALSE to build it as static libraries")
else()
if(SFML_OS_IOS)
set(BUILD_SHARED_LIBS FALSE)
elseif(SFML_OS_ANDROID)
set(BUILD_SHARED_LIBS TRUE)
endif()
endif()
# add an option for building the examples
if(NOT (SFML_OS_IOS OR SFML_OS_ANDROID))
sfml_set_option(SFML_BUILD_EXAMPLES FALSE BOOL "TRUE to build the SFML examples, FALSE to ignore them")
else()
set(SFML_BUILD_EXAMPLES FALSE)
endif()
# add an option for building the API documentation
sfml_set_option(SFML_BUILD_DOC FALSE BOOL "TRUE to generate the API documentation, FALSE to ignore it")
# add an option for choosing the OpenGL implementation
sfml_set_option(SFML_OPENGL_ES ${OPENGL_ES} BOOL "TRUE to use an OpenGL ES implementation, FALSE to use a desktop OpenGL implementation")
# Mac OS X specific options
if(SFML_OS_MACOSX)
# add an option to build frameworks instead of dylibs (release only)
sfml_set_option(SFML_BUILD_FRAMEWORKS FALSE BOOL "TRUE to build SFML as frameworks libraries (release only), FALSE to build according to BUILD_SHARED_LIBS")
# add an option to let the user specify a custom directory for frameworks installation (SFML, sndfile, ...)
sfml_set_option(CMAKE_INSTALL_FRAMEWORK_PREFIX "/Library/Frameworks" STRING "Frameworks installation directory")
# add an option to automatically install Xcode templates
sfml_set_option(SFML_INSTALL_XCODE_TEMPLATES FALSE BOOL "TRUE to automatically install the Xcode templates, FALSE to do nothing about it. The templates are compatible with Xcode 4 and 5.")
endif()
# Android options
if(SFML_OS_ANDROID)
# force usage of the STL port
set(ANDROID_USE_STLPORT TRUE)
# make sure there's the android library available
if (${ANDROID_NATIVE_API_LEVEL} LESS 9)
message(FATAL_ERROR "API level must be equal or greater than 9")
endif()
# install everything in $NDK/sources/ because this path is appended by the NDK (convenient)
set(CMAKE_INSTALL_PREFIX ${ANDROID_NDK}/sources/sfml)
# we install libs in a subdirectory named after the ABI (lib/mips/*.so)
set(LIB_SUFFIX "/${ANDROID_ABI}")
# this is a workaround to compile sfml-activity without stlport_shared as dependency
# we save the original compilation command line to restore it later in Macro.cmake
set(CMAKE_CXX_CREATE_SHARED_LIBRARY_WITH_STLPORT ${CMAKE_CXX_CREATE_SHARED_LIBRARY})
set(CMAKE_CXX_CREATE_SHARED_LIBRARY_WITHOUT_STLPORT "<CMAKE_CXX_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <SONAME_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>")
endif()
# define SFML_STATIC if the build type is not set to 'shared'
if(NOT BUILD_SHARED_LIBS)
add_definitions(-DSFML_STATIC)
endif()
# remove SL security warnings with Visual C++
if(SFML_COMPILER_MSVC)
add_definitions(-D_CRT_SECURE_NO_DEPRECATE)
endif()
# define SFML_OPENGL_ES if needed
if(SFML_OPENGL_ES)
add_definitions(-DSFML_OPENGL_ES)
add_definitions(-DGL_GLEXT_PROTOTYPES)
endif()
# define an option for choosing between static and dynamic C runtime (Windows only)
if(SFML_OS_WINDOWS)
sfml_set_option(SFML_USE_STATIC_STD_LIBS FALSE BOOL "TRUE to statically link to the standard libraries, FALSE to use them as DLLs")
# the following combination of flags is not valid
if (BUILD_SHARED_LIBS AND SFML_USE_STATIC_STD_LIBS)
message(FATAL_ERROR "BUILD_SHARED_LIBS and SFML_USE_STATIC_STD_LIBS cannot be used together")
endif()
# for VC++, we can apply it globally by modifying the compiler flags
if(SFML_COMPILER_MSVC AND SFML_USE_STATIC_STD_LIBS)
foreach(flag
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
if(${flag} MATCHES "/MD")
string(REGEX REPLACE "/MD" "/MT" ${flag} "${${flag}}")
endif()
endforeach()
endif()
endif()
# setup Mac OS X stuff
if(SFML_OS_MACOSX)
# SFML_BUILD_FRAMEWORKS needs two things:
# first, it's available only for release
# (because cmake currently doesn't allow specifying a custom framework name so XXX-d is not possible)
# secondly, it works only with BUILD_SHARED_LIBS enabled
if(SFML_BUILD_FRAMEWORKS)
# requirement #1
if(NOT CMAKE_BUILD_TYPE STREQUAL "Release")
message(FATAL_ERROR "CMAKE_BUILD_TYPE should be \"Release\" when SFML_BUILD_FRAMEWORKS is TRUE")
return()
endif()
# requirement #2
if(NOT BUILD_SHARED_LIBS)
message(FATAL_ERROR "BUILD_SHARED_LIBS should be TRUE when SFML_BUILD_FRAMEWORKS is TRUE")
return()
endif()
endif()
# configure Xcode templates
if(CMAKE_OSX_ARCHITECTURES)
# maybe multiple arches are present in CMAKE_OSX_ARCHITECTURES
# we simply need to replace ';' by ' ' (space) and store the result in XCODE_TEMPLATES_ARCH
string(REPLACE ";" " " XCODE_TEMPLATES_ARCH "${CMAKE_OSX_ARCHITECTURES}")
else()
# no arch was provided to cmake, so we use the default one
set(XCODE_TEMPLATES_ARCH "\$(NATIVE_ARCH_ACTUAL)")
endif()
endif()
if(SFML_OS_LINUX OR SFML_OS_FREEBSD)
set(PKGCONFIG_DIR lib${LIB_SUFFIX}/pkgconfig)
if(SFML_OS_FREEBSD)
set(PKGCONFIG_DIR libdata/pkgconfig)
endif()
if(BUILD_SHARED_LIBS)
sfml_set_option(SFML_INSTALL_PKGCONFIG_FILES FALSE BOOL "TRUE to automatically install pkg-config files so other projects can find SFML")
if(SFML_INSTALL_PKGCONFIG_FILES)
foreach(sfml_module IN ITEMS all system window graphics audio network)
CONFIGURE_FILE(
"tools/pkg-config/sfml-${sfml_module}.pc.in"
"tools/pkg-config/sfml-${sfml_module}.pc"
@ONLY)
INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/tools/pkg-config/sfml-${sfml_module}.pc"
DESTINATION "${CMAKE_INSTALL_PREFIX}/${PKGCONFIG_DIR}")
endforeach()
endif()
else()
if(SFML_INSTALL_PKGCONFIG_FILES)
message(WARNING "No pkg-config files are provided for the static SFML libraries (SFML_INSTALL_PKGCONFIG_FILES will be ignored).")
endif()
endif()
endif()
# enable project folders
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER "CMake")
# add the subdirectories
add_subdirectory(src/SFML)
if(SFML_BUILD_EXAMPLES)
add_subdirectory(examples)
endif()
if(SFML_BUILD_DOC)
add_subdirectory(doc)
endif()
# setup the install rules
if(NOT SFML_BUILD_FRAMEWORKS)
install(DIRECTORY include
DESTINATION .
COMPONENT devel
FILES_MATCHING PATTERN "*.hpp" PATTERN "*.inl")
else()
# find only "root" headers
file(GLOB SFML_HEADERS RELATIVE ${PROJECT_SOURCE_DIR} "include/SFML/*")
# in fact we have to fool cmake to copy all the headers in subdirectories
# to do that we have to add the "root" headers to the PUBLIC_HEADER
# then we can run a post script to copy the remaining headers
# we need a dummy file in order to compile the framework
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp
COMMAND touch ${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp)
set(SFML_SOURCES ${SFML_HEADERS})
list(APPEND SFML_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp)
# create SFML.framework
add_library(SFML ${SFML_SOURCES})
# edit target properties
set_target_properties(SFML PROPERTIES
FRAMEWORK TRUE
FRAMEWORK_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
MACOSX_FRAMEWORK_IDENTIFIER org.sfml-dev.SFML
MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
MACOSX_FRAMEWORK_BUNDLE_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
PUBLIC_HEADER "${SFML_HEADERS}")
# add the remaining headers
add_custom_command(TARGET SFML
POST_BUILD
COMMAND cp -r ${PROJECT_SOURCE_DIR}/include/SFML/* $<TARGET_FILE_DIR:SFML>/Headers)
# adapt install directory to allow distributing dylibs/frameworks in users frameworks/application bundle
# NOTE: it's not required to link agains SFML.framework
set_target_properties(SFML PROPERTIES
BUILD_WITH_INSTALL_RPATH 1
INSTALL_NAME_DIR "@executable_path/../Frameworks")
# install rule
install(TARGETS SFML
FRAMEWORK DESTINATION ${CMAKE_INSTALL_FRAMEWORK_PREFIX}
COMPONENT devel)
endif()
install(FILES license.txt DESTINATION ${INSTALL_MISC_DIR})
install(FILES readme.txt DESTINATION ${INSTALL_MISC_DIR})
if(NOT SFML_OS_ANDROID)
install(FILES cmake/Modules/FindSFML.cmake DESTINATION ${INSTALL_MISC_DIR}/cmake/Modules)
endif()
# install 3rd-party libraries and tools
if(SFML_OS_WINDOWS)
# install the binaries of SFML dependencies
if(ARCH_32BITS)
install(DIRECTORY extlibs/bin/x86/ DESTINATION bin)
if(SFML_COMPILER_MSVC)
install(DIRECTORY extlibs/libs-msvc/x86/ DESTINATION lib)
else()
install(DIRECTORY extlibs/libs-mingw/x86/ DESTINATION lib)
endif()
elseif(ARCH_64BITS)
install(DIRECTORY extlibs/bin/x64/ DESTINATION bin)
if(SFML_COMPILER_MSVC)
install(DIRECTORY extlibs/libs-msvc/x64/ DESTINATION lib)
else()
install(DIRECTORY extlibs/libs-mingw/x64/ DESTINATION lib)
endif()
endif()
elseif(SFML_OS_MACOSX)
# install the non-standard frameworks SFML depends on
install(DIRECTORY extlibs/libs-osx/Frameworks/sndfile.framework DESTINATION ${CMAKE_INSTALL_FRAMEWORK_PREFIX})
install(DIRECTORY extlibs/libs-osx/Frameworks/freetype.framework DESTINATION ${CMAKE_INSTALL_FRAMEWORK_PREFIX})
# install the Xcode templates if requested
if(SFML_INSTALL_XCODE_TEMPLATES)
configure_file(
"tools/xcode/templates/SFML/SFML Compiler.xctemplate/TemplateInfo.plist.in"
"${CMAKE_CURRENT_BINARY_DIR}/tools/xcode/templates/SFML/SFML Compiler.xctemplate/TemplateInfo.plist"
@ONLY)
install(DIRECTORY "tools/xcode/templates/SFML" "${CMAKE_CURRENT_BINARY_DIR}/tools/xcode/templates/SFML"
DESTINATION /Library/Developer/Xcode/Templates
PATTERN "*.in" EXCLUDE)
endif()
elseif(SFML_OS_IOS)
# fix CMake install rules broken for iOS (see http://public.kitware.com/Bug/view.php?id=12506)
if(SFML_OS_IOS)
install(DIRECTORY "${CMAKE_BINARY_DIR}/lib/\$ENV{CONFIGURATION}/" DESTINATION lib${LIB_SUFFIX})
endif()
# since the iOS libraries are built as static, we must install the SFML dependencies
# too so that the end user can easily link them to its final application
install(FILES extlibs/libs-ios/libfreetype.a extlibs/libs-ios/libjpeg.a DESTINATION lib)
elseif(SFML_OS_ANDROID)
# install extlibs
install(DIRECTORY extlibs/libs-android/${ANDROID_ABI} DESTINATION extlibs/lib)
install(FILES extlibs/Android.mk DESTINATION extlibs)
# install Android.mk so the NDK knows how to set up SFML
install(FILES src/SFML/Android.mk DESTINATION .)
endif()

View file

@ -1,117 +1,117 @@
# detect the OS
if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
set(SFML_OS_WINDOWS 1)
# don't use the OpenGL ES implementation on Windows
set(OPENGL_ES 0)
# detect the architecture (note: this test won't work for cross-compilation)
include(CheckTypeSize)
check_type_size(void* SIZEOF_VOID_PTR)
if("${SIZEOF_VOID_PTR}" STREQUAL "4")
set(ARCH_32BITS 1)
elseif("${SIZEOF_VOID_PTR}" STREQUAL "8")
set(ARCH_64BITS 1)
else()
message(FATAL_ERROR "Unsupported architecture")
return()
# detect the OS
if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
set(SFML_OS_WINDOWS 1)
# don't use the OpenGL ES implementation on Windows
set(OPENGL_ES 0)
# detect the architecture (note: this test won't work for cross-compilation)
include(CheckTypeSize)
check_type_size(void* SIZEOF_VOID_PTR)
if("${SIZEOF_VOID_PTR}" STREQUAL "4")
set(ARCH_32BITS 1)
elseif("${SIZEOF_VOID_PTR}" STREQUAL "8")
set(ARCH_64BITS 1)
else()
message(FATAL_ERROR "Unsupported architecture")
return()
endif()
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
set(SFML_OS_UNIX 1)
if(ANDROID)
set(SFML_OS_ANDROID 1)
# use the OpenGL ES implementation on Android
set(OPENGL_ES 1)
else()
set(SFML_OS_LINUX 1)
# don't use the OpenGL ES implementation on Linux
set(OPENGL_ES 0)
if(ANDROID)
set(SFML_OS_ANDROID 1)
# use the OpenGL ES implementation on Android
set(OPENGL_ES 1)
else()
set(SFML_OS_LINUX 1)
# don't use the OpenGL ES implementation on Linux
set(OPENGL_ES 0)
endif()
elseif(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
set(SFML_OS_FREEBSD 1)
# don't use the OpenGL ES implementation on FreeBSD
set(OPENGL_ES 0)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
set(SFML_OS_FREEBSD 1)
# don't use the OpenGL ES implementation on FreeBSD
set(OPENGL_ES 0)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
if(IOS)
set(SFML_OS_IOS 1)
# set the target framework and platforms
set(CMAKE_OSX_SYSROOT "iphoneos")
set(CMAKE_OSX_ARCHITECTURES "armv6;armv7;i386")
set(CMAKE_XCODE_EFFECTIVE_PLATFORMS "-iphoneos;-iphonesimulator")
# help the compiler detection script below
set(CMAKE_COMPILER_IS_GNUCXX 1)
# use the OpenGL ES implementation on iOS
set(OPENGL_ES 1)
else()
set(SFML_OS_MACOSX 1)
# don't use the OpenGL ES implementation on Mac OS X
set(OPENGL_ES 0)
# detect OS X version. (use '/usr/bin/sw_vers -productVersion' to extract V from '10.V.x'.)
EXEC_PROGRAM(/usr/bin/sw_vers ARGS -productVersion OUTPUT_VARIABLE MACOSX_VERSION_RAW)
# set the target framework and platforms
set(CMAKE_OSX_SYSROOT "iphoneos")
set(CMAKE_OSX_ARCHITECTURES "armv6;armv7;i386")
set(CMAKE_XCODE_EFFECTIVE_PLATFORMS "-iphoneos;-iphonesimulator")
# help the compiler detection script below
set(CMAKE_COMPILER_IS_GNUCXX 1)
# use the OpenGL ES implementation on iOS
set(OPENGL_ES 1)
else()
set(SFML_OS_MACOSX 1)
# don't use the OpenGL ES implementation on Mac OS X
set(OPENGL_ES 0)
# detect OS X version. (use '/usr/bin/sw_vers -productVersion' to extract V from '10.V.x'.)
EXEC_PROGRAM(/usr/bin/sw_vers ARGS -productVersion OUTPUT_VARIABLE MACOSX_VERSION_RAW)
STRING(REGEX REPLACE "10\\.([0-9]+).*" "\\1" MACOSX_VERSION "${MACOSX_VERSION_RAW}")
if(${MACOSX_VERSION} LESS 7)
message(FATAL_ERROR "Unsupported version of OS X: ${MACOSX_VERSION_RAW}")
if(${MACOSX_VERSION} LESS 7)
message(FATAL_ERROR "Unsupported version of OS X: ${MACOSX_VERSION_RAW}")
return()
endif()
endif()
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Android")
set(SFML_OS_ANDROID 1)
# use the OpenGL ES implementation on Android
set(OPENGL_ES 1)
else()
message(FATAL_ERROR "Unsupported operating system")
return()
endif()
# detect the compiler and its version
# Note: on some platforms (OS X), CMAKE_COMPILER_IS_GNUCXX is true
# even when CLANG is used, therefore the Clang test is done first
if(CMAKE_CXX_COMPILER MATCHES ".*clang[+][+]" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
# CMAKE_CXX_COMPILER_ID is an internal CMake variable subject to change,
# but there is no other way to detect CLang at the moment
set(SFML_COMPILER_CLANG 1)
execute_process(COMMAND "${CMAKE_CXX_COMPILER}" "--version" OUTPUT_VARIABLE CLANG_VERSION_OUTPUT)
string(REGEX REPLACE ".*clang version ([0-9]+\\.[0-9]+).*" "\\1" SFML_CLANG_VERSION "${CLANG_VERSION_OUTPUT}")
elseif(CMAKE_COMPILER_IS_GNUCXX)
set(SFML_COMPILER_GCC 1)
execute_process(COMMAND "${CMAKE_CXX_COMPILER}" "-dumpversion" OUTPUT_VARIABLE GCC_VERSION_OUTPUT)
string(REGEX REPLACE "([0-9]+\\.[0-9]+).*" "\\1" SFML_GCC_VERSION "${GCC_VERSION_OUTPUT}")
execute_process(COMMAND "${CMAKE_CXX_COMPILER}" "--version" OUTPUT_VARIABLE GCC_COMPILER_VERSION)
string(REGEX MATCHALL ".*(tdm[64]*-[1-9]).*" SFML_COMPILER_GCC_TDM "${GCC_COMPILER_VERSION}")
execute_process(COMMAND "${CMAKE_CXX_COMPILER}" "-dumpmachine" OUTPUT_VARIABLE GCC_MACHINE)
string(STRIP "${GCC_MACHINE}" GCC_MACHINE)
if(${GCC_MACHINE} MATCHES ".*w64.*")
set(SFML_COMPILER_GCC_W64 1)
endif()
elseif(MSVC)
set(SFML_COMPILER_MSVC 1)
if(MSVC_VERSION EQUAL 1400)
set(SFML_MSVC_VERSION 8)
elseif(MSVC_VERSION EQUAL 1500)
set(SFML_MSVC_VERSION 9)
elseif(MSVC_VERSION EQUAL 1600)
set(SFML_MSVC_VERSION 10)
elseif(MSVC_VERSION EQUAL 1700)
set(SFML_MSVC_VERSION 11)
elseif(MSVC_VERSION EQUAL 1800)
set(SFML_MSVC_VERSION 12)
endif()
else()
message(FATAL_ERROR "Unsupported compiler")
return()
endif()
endif()
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Android")
set(SFML_OS_ANDROID 1)
# define the install directory for miscellaneous files
# use the OpenGL ES implementation on Android
set(OPENGL_ES 1)
else()
message(FATAL_ERROR "Unsupported operating system")
return()
endif()
# detect the compiler and its version
# Note: on some platforms (OS X), CMAKE_COMPILER_IS_GNUCXX is true
# even when CLANG is used, therefore the Clang test is done first
if(CMAKE_CXX_COMPILER MATCHES ".*clang[+][+]" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
# CMAKE_CXX_COMPILER_ID is an internal CMake variable subject to change,
# but there is no other way to detect CLang at the moment
set(SFML_COMPILER_CLANG 1)
execute_process(COMMAND "${CMAKE_CXX_COMPILER}" "--version" OUTPUT_VARIABLE CLANG_VERSION_OUTPUT)
string(REGEX REPLACE ".*clang version ([0-9]+\\.[0-9]+).*" "\\1" SFML_CLANG_VERSION "${CLANG_VERSION_OUTPUT}")
elseif(CMAKE_COMPILER_IS_GNUCXX)
set(SFML_COMPILER_GCC 1)
execute_process(COMMAND "${CMAKE_CXX_COMPILER}" "-dumpversion" OUTPUT_VARIABLE GCC_VERSION_OUTPUT)
string(REGEX REPLACE "([0-9]+\\.[0-9]+).*" "\\1" SFML_GCC_VERSION "${GCC_VERSION_OUTPUT}")
execute_process(COMMAND "${CMAKE_CXX_COMPILER}" "--version" OUTPUT_VARIABLE GCC_COMPILER_VERSION)
string(REGEX MATCHALL ".*(tdm[64]*-[1-9]).*" SFML_COMPILER_GCC_TDM "${GCC_COMPILER_VERSION}")
execute_process(COMMAND "${CMAKE_CXX_COMPILER}" "-dumpmachine" OUTPUT_VARIABLE GCC_MACHINE)
string(STRIP "${GCC_MACHINE}" GCC_MACHINE)
if(${GCC_MACHINE} MATCHES ".*w64.*")
set(SFML_COMPILER_GCC_W64 1)
endif()
elseif(MSVC)
set(SFML_COMPILER_MSVC 1)
if(MSVC_VERSION EQUAL 1400)
set(SFML_MSVC_VERSION 8)
elseif(MSVC_VERSION EQUAL 1500)
set(SFML_MSVC_VERSION 9)
elseif(MSVC_VERSION EQUAL 1600)
set(SFML_MSVC_VERSION 10)
elseif(MSVC_VERSION EQUAL 1700)
set(SFML_MSVC_VERSION 11)
elseif(MSVC_VERSION EQUAL 1800)
set(SFML_MSVC_VERSION 12)
endif()
else()
message(FATAL_ERROR "Unsupported compiler")
return()
endif()
# define the install directory for miscellaneous files
if(SFML_OS_WINDOWS OR SFML_OS_IOS)
set(INSTALL_MISC_DIR .)
elseif(SFML_OS_LINUX OR SFML_OS_FREEBSD OR SFML_OS_MACOSX)
set(INSTALL_MISC_DIR share/SFML)
elseif(SFML_OS_ANDROID)
set(INSTALL_MISC_DIR ${ANDROID_NDK}/sources/sfml)
endif()
set(INSTALL_MISC_DIR .)
elseif(SFML_OS_LINUX OR SFML_OS_FREEBSD OR SFML_OS_MACOSX)
set(INSTALL_MISC_DIR share/SFML)
elseif(SFML_OS_ANDROID)
set(INSTALL_MISC_DIR ${ANDROID_NDK}/sources/sfml)
endif()

View file

@ -1,178 +1,178 @@
include(CMakeParseArguments)
# add a new target which is a SFML library
# ex: sfml_add_library(sfml-graphics
# SOURCES sprite.cpp image.cpp ...
# DEPENDS sfml-window sfml-system
# EXTERNAL_LIBS opengl freetype ...)
macro(sfml_add_library target)
# parse the arguments
cmake_parse_arguments(THIS "" "" "SOURCES;DEPENDS;EXTERNAL_LIBS" ${ARGN})
include(CMakeParseArguments)
# add a new target which is a SFML library
# ex: sfml_add_library(sfml-graphics
# SOURCES sprite.cpp image.cpp ...
# DEPENDS sfml-window sfml-system
# EXTERNAL_LIBS opengl freetype ...)
macro(sfml_add_library target)
# parse the arguments
cmake_parse_arguments(THIS "" "" "SOURCES;DEPENDS;EXTERNAL_LIBS" ${ARGN})
# create the target
add_library(${target} ${THIS_SOURCES})
# define the export symbol of the module
string(REPLACE "-" "_" NAME_UPPER "${target}")
string(TOUPPER "${NAME_UPPER}" NAME_UPPER)
set_target_properties(${target} PROPERTIES DEFINE_SYMBOL ${NAME_UPPER}_EXPORTS)
# adjust the output file prefix/suffix to match our conventions
if(BUILD_SHARED_LIBS)
if(SFML_OS_WINDOWS)
# include the major version number in Windows shared library names (but not import library names)
set_target_properties(${target} PROPERTIES DEBUG_POSTFIX -d)
set_target_properties(${target} PROPERTIES SUFFIX "-${VERSION_MAJOR}${CMAKE_SHARED_LIBRARY_SUFFIX}")
else()
set_target_properties(${target} PROPERTIES DEBUG_POSTFIX -d)
endif()
if (SFML_OS_WINDOWS AND SFML_COMPILER_GCC)
# on Windows/gcc get rid of "lib" prefix for shared libraries,
# and transform the ".dll.a" suffix into ".a" for import libraries
set_target_properties(${target} PROPERTIES PREFIX "")
set_target_properties(${target} PROPERTIES IMPORT_SUFFIX ".a")
endif()
else()
set_target_properties(${target} PROPERTIES DEBUG_POSTFIX -s-d)
set_target_properties(${target} PROPERTIES RELEASE_POSTFIX -s)
set_target_properties(${target} PROPERTIES MINSIZEREL_POSTFIX -s)
endif()
# set the version and soversion of the target (for compatible systems -- mostly Linuxes)
# except for Android which strips soversion suffixes
if(NOT SFML_OS_ANDROID)
set_target_properties(${target} PROPERTIES SOVERSION ${VERSION_MAJOR})
set_target_properties(${target} PROPERTIES VERSION ${VERSION_MAJOR}.${VERSION_MINOR})
endif()
# set the target's folder (for IDEs that support it, e.g. Visual Studio)
set_target_properties(${target} PROPERTIES FOLDER "SFML")
# for gcc >= 4.0 on Windows, apply the SFML_USE_STATIC_STD_LIBS option if it is enabled
if(SFML_OS_WINDOWS AND SFML_COMPILER_GCC AND NOT SFML_GCC_VERSION VERSION_LESS "4")
if(SFML_USE_STATIC_STD_LIBS AND NOT SFML_COMPILER_GCC_TDM)
set_target_properties(${target} PROPERTIES LINK_FLAGS "-static-libgcc -static-libstdc++")
elseif(NOT SFML_USE_STATIC_STD_LIBS AND SFML_COMPILER_GCC_TDM)
set_target_properties(${target} PROPERTIES LINK_FLAGS "-shared-libgcc -shared-libstdc++")
endif()
endif()
# if using gcc >= 4.0 or clang >= 3.0 on a non-Windows platform, we must hide public symbols by default
# (exported ones are explicitely marked)
if(NOT SFML_OS_WINDOWS AND ((SFML_COMPILER_GCC AND NOT SFML_GCC_VERSION VERSION_LESS "4") OR (SFML_COMPILER_CLANG AND NOT SFML_CLANG_VERSION VERSION_LESS "3")))
set_target_properties(${target} PROPERTIES COMPILE_FLAGS -fvisibility=hidden)
endif()
# link the target to its SFML dependencies
if(THIS_DEPENDS)
target_link_libraries(${target} ${THIS_DEPENDS})
endif()
# build frameworks or dylibs
if(SFML_OS_MACOSX AND BUILD_SHARED_LIBS)
if(SFML_BUILD_FRAMEWORKS)
# adapt target to build frameworks instead of dylibs
set_target_properties(${target} PROPERTIES
FRAMEWORK TRUE
FRAMEWORK_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
MACOSX_FRAMEWORK_IDENTIFIER org.sfml-dev.${target}
MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
MACOSX_FRAMEWORK_BUNDLE_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH})
endif()
# adapt install directory to allow distributing dylibs/frameworks in users frameworks/application bundle
set_target_properties(${target} PROPERTIES
BUILD_WITH_INSTALL_RPATH 1
INSTALL_NAME_DIR "@executable_path/../Frameworks")
endif()
# enable automatic reference counting on iOS
if (SFML_OS_IOS)
set_target_properties(${target} PROPERTIES XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC YES)
endif()
# sfml-activity library is our bootstrap activity and must not depend on stlport_shared
# (otherwise Android will fail to load it)
if (SFML_OS_ANDROID)
if (${target} MATCHES "sfml-activity")
set_target_properties(${target} PROPERTIES COMPILE_FLAGS -fpermissive)
set_target_properties(${target} PROPERTIES LINK_FLAGS "-landroid -llog")
set(CMAKE_CXX_CREATE_SHARED_LIBRARY ${CMAKE_CXX_CREATE_SHARED_LIBRARY_WITHOUT_STLPORT})
else()
set(CMAKE_CXX_CREATE_SHARED_LIBRARY ${CMAKE_CXX_CREATE_SHARED_LIBRARY_WITH_STLPORT})
endif()
endif()
# link the target to its external dependencies
if(THIS_EXTERNAL_LIBS)
target_link_libraries(${target} ${THIS_EXTERNAL_LIBS})
endif()
# add the install rule
install(TARGETS ${target}
RUNTIME DESTINATION bin COMPONENT bin
LIBRARY DESTINATION lib${LIB_SUFFIX} COMPONENT bin
ARCHIVE DESTINATION lib${LIB_SUFFIX} COMPONENT devel
FRAMEWORK DESTINATION ${CMAKE_INSTALL_FRAMEWORK_PREFIX} COMPONENT bin)
endmacro()
# add a new target which is a SFML example
# ex: sfml_add_example(ftp
# SOURCES ftp.cpp ...
# DEPENDS sfml-network sfml-system)
macro(sfml_add_example target)
# parse the arguments
cmake_parse_arguments(THIS "GUI_APP" "" "SOURCES;DEPENDS" ${ARGN})
# set a source group for the source files
source_group("" FILES ${THIS_SOURCES})
# create the target
add_library(${target} ${THIS_SOURCES})
# define the export symbol of the module
string(REPLACE "-" "_" NAME_UPPER "${target}")
string(TOUPPER "${NAME_UPPER}" NAME_UPPER)
set_target_properties(${target} PROPERTIES DEFINE_SYMBOL ${NAME_UPPER}_EXPORTS)
# adjust the output file prefix/suffix to match our conventions
if(BUILD_SHARED_LIBS)
if(SFML_OS_WINDOWS)
# include the major version number in Windows shared library names (but not import library names)
set_target_properties(${target} PROPERTIES DEBUG_POSTFIX -d)
set_target_properties(${target} PROPERTIES SUFFIX "-${VERSION_MAJOR}${CMAKE_SHARED_LIBRARY_SUFFIX}")
else()
set_target_properties(${target} PROPERTIES DEBUG_POSTFIX -d)
endif()
if (SFML_OS_WINDOWS AND SFML_COMPILER_GCC)
# on Windows/gcc get rid of "lib" prefix for shared libraries,
# and transform the ".dll.a" suffix into ".a" for import libraries
set_target_properties(${target} PROPERTIES PREFIX "")
set_target_properties(${target} PROPERTIES IMPORT_SUFFIX ".a")
endif()
else()
set_target_properties(${target} PROPERTIES DEBUG_POSTFIX -s-d)
set_target_properties(${target} PROPERTIES RELEASE_POSTFIX -s)
set_target_properties(${target} PROPERTIES MINSIZEREL_POSTFIX -s)
endif()
# set the version and soversion of the target (for compatible systems -- mostly Linuxes)
# except for Android which strips soversion suffixes
if(NOT SFML_OS_ANDROID)
set_target_properties(${target} PROPERTIES SOVERSION ${VERSION_MAJOR})
set_target_properties(${target} PROPERTIES VERSION ${VERSION_MAJOR}.${VERSION_MINOR})
endif()
# set the target's folder (for IDEs that support it, e.g. Visual Studio)
set_target_properties(${target} PROPERTIES FOLDER "SFML")
# for gcc >= 4.0 on Windows, apply the SFML_USE_STATIC_STD_LIBS option if it is enabled
if(SFML_OS_WINDOWS AND SFML_COMPILER_GCC AND NOT SFML_GCC_VERSION VERSION_LESS "4")
if(SFML_USE_STATIC_STD_LIBS AND NOT SFML_COMPILER_GCC_TDM)
set_target_properties(${target} PROPERTIES LINK_FLAGS "-static-libgcc -static-libstdc++")
elseif(NOT SFML_USE_STATIC_STD_LIBS AND SFML_COMPILER_GCC_TDM)
set_target_properties(${target} PROPERTIES LINK_FLAGS "-shared-libgcc -shared-libstdc++")
endif()
endif()
# if using gcc >= 4.0 or clang >= 3.0 on a non-Windows platform, we must hide public symbols by default
# (exported ones are explicitely marked)
if(NOT SFML_OS_WINDOWS AND ((SFML_COMPILER_GCC AND NOT SFML_GCC_VERSION VERSION_LESS "4") OR (SFML_COMPILER_CLANG AND NOT SFML_CLANG_VERSION VERSION_LESS "3")))
set_target_properties(${target} PROPERTIES COMPILE_FLAGS -fvisibility=hidden)
endif()
# link the target to its SFML dependencies
if(THIS_DEPENDS)
target_link_libraries(${target} ${THIS_DEPENDS})
endif()
# build frameworks or dylibs
if(SFML_OS_MACOSX AND BUILD_SHARED_LIBS)
if(SFML_BUILD_FRAMEWORKS)
# adapt target to build frameworks instead of dylibs
set_target_properties(${target} PROPERTIES
FRAMEWORK TRUE
FRAMEWORK_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
MACOSX_FRAMEWORK_IDENTIFIER org.sfml-dev.${target}
MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
MACOSX_FRAMEWORK_BUNDLE_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH})
endif()
# adapt install directory to allow distributing dylibs/frameworks in users frameworks/application bundle
set_target_properties(${target} PROPERTIES
BUILD_WITH_INSTALL_RPATH 1
INSTALL_NAME_DIR "@executable_path/../Frameworks")
endif()
# enable automatic reference counting on iOS
if (SFML_OS_IOS)
set_target_properties(${target} PROPERTIES XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC YES)
endif()
# sfml-activity library is our bootstrap activity and must not depend on stlport_shared
# (otherwise Android will fail to load it)
if (SFML_OS_ANDROID)
if (${target} MATCHES "sfml-activity")
set_target_properties(${target} PROPERTIES COMPILE_FLAGS -fpermissive)
set_target_properties(${target} PROPERTIES LINK_FLAGS "-landroid -llog")
set(CMAKE_CXX_CREATE_SHARED_LIBRARY ${CMAKE_CXX_CREATE_SHARED_LIBRARY_WITHOUT_STLPORT})
else()
set(CMAKE_CXX_CREATE_SHARED_LIBRARY ${CMAKE_CXX_CREATE_SHARED_LIBRARY_WITH_STLPORT})
endif()
endif()
# link the target to its external dependencies
if(THIS_EXTERNAL_LIBS)
target_link_libraries(${target} ${THIS_EXTERNAL_LIBS})
endif()
# add the install rule
install(TARGETS ${target}
RUNTIME DESTINATION bin COMPONENT bin
LIBRARY DESTINATION lib${LIB_SUFFIX} COMPONENT bin
ARCHIVE DESTINATION lib${LIB_SUFFIX} COMPONENT devel
FRAMEWORK DESTINATION ${CMAKE_INSTALL_FRAMEWORK_PREFIX} COMPONENT bin)
endmacro()
# add a new target which is a SFML example
# ex: sfml_add_example(ftp
# SOURCES ftp.cpp ...
# DEPENDS sfml-network sfml-system)
macro(sfml_add_example target)
# parse the arguments
cmake_parse_arguments(THIS "GUI_APP" "" "SOURCES;DEPENDS" ${ARGN})
# set a source group for the source files
source_group("" FILES ${THIS_SOURCES})
# create the target
if(THIS_GUI_APP AND SFML_OS_WINDOWS)
add_executable(${target} WIN32 ${THIS_SOURCES})
target_link_libraries(${target} sfml-main)
else()
add_executable(${target} ${THIS_SOURCES})
endif()
# set the debug suffix
set_target_properties(${target} PROPERTIES DEBUG_POSTFIX -d)
# set the target's folder (for IDEs that support it, e.g. Visual Studio)
set_target_properties(${target} PROPERTIES FOLDER "Examples")
# for gcc >= 4.0 on Windows, apply the SFML_USE_STATIC_STD_LIBS option if it is enabled
if(SFML_OS_WINDOWS AND SFML_COMPILER_GCC AND NOT SFML_GCC_VERSION VERSION_LESS "4")
if(SFML_USE_STATIC_STD_LIBS AND NOT SFML_COMPILER_GCC_TDM)
set_target_properties(${target} PROPERTIES LINK_FLAGS "-static-libgcc -static-libstdc++")
elseif(NOT SFML_USE_STATIC_STD_LIBS AND SFML_COMPILER_GCC_TDM)
set_target_properties(${target} PROPERTIES LINK_FLAGS "-shared-libgcc -shared-libstdc++")
endif()
endif()
# link the target to its SFML dependencies
if(THIS_DEPENDS)
target_link_libraries(${target} ${THIS_DEPENDS})
endif()
# add the install rule
install(TARGETS ${target}
RUNTIME DESTINATION ${INSTALL_MISC_DIR}/examples/${target} COMPONENT examples
BUNDLE DESTINATION ${INSTALL_MISC_DIR}/examples/${target} COMPONENT examples)
# install the example's source code
install(FILES ${THIS_SOURCES}
DESTINATION ${INSTALL_MISC_DIR}/examples/${target}
COMPONENT examples)
# install the example's resources as well
set(EXAMPLE_RESOURCES "${CMAKE_SOURCE_DIR}/examples/${target}/resources")
if(EXISTS ${EXAMPLE_RESOURCES})
install(DIRECTORY ${EXAMPLE_RESOURCES}
DESTINATION ${INSTALL_MISC_DIR}/examples/${target}
COMPONENT examples)
endif()
endmacro()
add_executable(${target} WIN32 ${THIS_SOURCES})
target_link_libraries(${target} sfml-main)
else()
add_executable(${target} ${THIS_SOURCES})
endif()
# set the debug suffix
set_target_properties(${target} PROPERTIES DEBUG_POSTFIX -d)
# set the target's folder (for IDEs that support it, e.g. Visual Studio)
set_target_properties(${target} PROPERTIES FOLDER "Examples")
# for gcc >= 4.0 on Windows, apply the SFML_USE_STATIC_STD_LIBS option if it is enabled
if(SFML_OS_WINDOWS AND SFML_COMPILER_GCC AND NOT SFML_GCC_VERSION VERSION_LESS "4")
if(SFML_USE_STATIC_STD_LIBS AND NOT SFML_COMPILER_GCC_TDM)
set_target_properties(${target} PROPERTIES LINK_FLAGS "-static-libgcc -static-libstdc++")
elseif(NOT SFML_USE_STATIC_STD_LIBS AND SFML_COMPILER_GCC_TDM)
set_target_properties(${target} PROPERTIES LINK_FLAGS "-shared-libgcc -shared-libstdc++")
endif()
endif()
# link the target to its SFML dependencies
if(THIS_DEPENDS)
target_link_libraries(${target} ${THIS_DEPENDS})
endif()
# add the install rule
install(TARGETS ${target}
RUNTIME DESTINATION ${INSTALL_MISC_DIR}/examples/${target} COMPONENT examples
BUNDLE DESTINATION ${INSTALL_MISC_DIR}/examples/${target} COMPONENT examples)
# install the example's source code
install(FILES ${THIS_SOURCES}
DESTINATION ${INSTALL_MISC_DIR}/examples/${target}
COMPONENT examples)
# install the example's resources as well
set(EXAMPLE_RESOURCES "${CMAKE_SOURCE_DIR}/examples/${target}/resources")
if(EXISTS ${EXAMPLE_RESOURCES})
install(DIRECTORY ${EXAMPLE_RESOURCES}
DESTINATION ${INSTALL_MISC_DIR}/examples/${target}
COMPONENT examples)
endif()
endmacro()

View file

@ -1,14 +1,14 @@
#
# Try to find EGL library and include path.
# Once done this will define
#
# EGL_FOUND
# EGL_INCLUDE_PATH
# EGL_LIBRARY
#
find_path(EGL_INCLUDE_DIR EGL/egl.h)
find_library(EGL_LIBRARY NAMES EGL)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(EGL DEFAULT_MSG EGL_LIBRARY EGL_INCLUDE_DIR)
#
# Try to find EGL library and include path.
# Once done this will define
#
# EGL_FOUND
# EGL_INCLUDE_PATH
# EGL_LIBRARY
#
find_path(EGL_INCLUDE_DIR EGL/egl.h)
find_library(EGL_LIBRARY NAMES EGL)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(EGL DEFAULT_MSG EGL_LIBRARY EGL_INCLUDE_DIR)

View file

@ -1,14 +1,14 @@
#
# Try to find GLES library and include path.
# Once done this will define
#
# GLES_FOUND
# GLES_INCLUDE_PATH
# GLES_LIBRARY
#
find_path(GLES_INCLUDE_DIR GLES/gl.h)
find_library(GLES_LIBRARY NAMES GLESv1_CM)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(GLES DEFAULT_MSG GLES_LIBRARY GLES_INCLUDE_DIR)
#
# Try to find GLES library and include path.
# Once done this will define
#
# GLES_FOUND
# GLES_INCLUDE_PATH
# GLES_LIBRARY
#
find_path(GLES_INCLUDE_DIR GLES/gl.h)
find_library(GLES_LIBRARY NAMES GLESv1_CM)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(GLES DEFAULT_MSG GLES_LIBRARY GLES_INCLUDE_DIR)

View file

@ -1,65 +1,65 @@
#
# Try to find GLEW library and include path.
# Once done this will define
#
# GLEW_FOUND
# GLEW_INCLUDE_PATH
# GLEW_LIBRARY
#
IF (WIN32)
FIND_PATH( GLEW_INCLUDE_PATH GL/glew.h
$ENV{PROGRAMFILES}/GLEW/include
${GLEW_ROOT_DIR}/include
DOC "The directory where GL/glew.h resides")
IF (NV_SYSTEM_PROCESSOR STREQUAL "AMD64")
FIND_LIBRARY( GLEW_LIBRARY
NAMES glew64 glew64s
PATHS
$ENV{PROGRAMFILES}/GLEW/lib
${PROJECT_SOURCE_DIR}/src/nvgl/glew/bin
${PROJECT_SOURCE_DIR}/src/nvgl/glew/lib
DOC "The GLEW library (64-bit)"
)
ELSE(NV_SYSTEM_PROCESSOR STREQUAL "AMD64")
FIND_LIBRARY( GLEW_LIBRARY
NAMES glew GLEW glew32 glew32s
PATHS
$ENV{PROGRAMFILES}/GLEW/lib
${PROJECT_SOURCE_DIR}/src/nvgl/glew/bin
${PROJECT_SOURCE_DIR}/src/nvgl/glew/lib
DOC "The GLEW library"
)
ENDIF(NV_SYSTEM_PROCESSOR STREQUAL "AMD64")
ELSE (WIN32)
FIND_PATH( GLEW_INCLUDE_PATH GL/glew.h
/usr/include
/usr/local/include
/sw/include
/opt/local/include
${GLEW_ROOT_DIR}/include
DOC "The directory where GL/glew.h resides")
FIND_LIBRARY( GLEW_LIBRARY
NAMES GLEW glew
PATHS
/usr/lib64
/usr/lib
/usr/local/lib64
/usr/local/lib
/sw/lib
/opt/local/lib
${GLEW_ROOT_DIR}/lib
DOC "The GLEW library")
ENDIF (WIN32)
SET(GLEW_FOUND "NO")
IF (GLEW_INCLUDE_PATH AND GLEW_LIBRARY)
SET(GLEW_LIBRARIES ${GLEW_LIBRARY})
SET(GLEW_FOUND "YES")
ENDIF (GLEW_INCLUDE_PATH AND GLEW_LIBRARY)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(GLEW DEFAULT_MSG GLEW_LIBRARY GLEW_INCLUDE_PATH)
#
# Try to find GLEW library and include path.
# Once done this will define
#
# GLEW_FOUND
# GLEW_INCLUDE_PATH
# GLEW_LIBRARY
#
IF (WIN32)
FIND_PATH( GLEW_INCLUDE_PATH GL/glew.h
$ENV{PROGRAMFILES}/GLEW/include
${GLEW_ROOT_DIR}/include
DOC "The directory where GL/glew.h resides")
IF (NV_SYSTEM_PROCESSOR STREQUAL "AMD64")
FIND_LIBRARY( GLEW_LIBRARY
NAMES glew64 glew64s
PATHS
$ENV{PROGRAMFILES}/GLEW/lib
${PROJECT_SOURCE_DIR}/src/nvgl/glew/bin
${PROJECT_SOURCE_DIR}/src/nvgl/glew/lib
DOC "The GLEW library (64-bit)"
)
ELSE(NV_SYSTEM_PROCESSOR STREQUAL "AMD64")
FIND_LIBRARY( GLEW_LIBRARY
NAMES glew GLEW glew32 glew32s
PATHS
$ENV{PROGRAMFILES}/GLEW/lib
${PROJECT_SOURCE_DIR}/src/nvgl/glew/bin
${PROJECT_SOURCE_DIR}/src/nvgl/glew/lib
DOC "The GLEW library"
)
ENDIF(NV_SYSTEM_PROCESSOR STREQUAL "AMD64")
ELSE (WIN32)
FIND_PATH( GLEW_INCLUDE_PATH GL/glew.h
/usr/include
/usr/local/include
/sw/include
/opt/local/include
${GLEW_ROOT_DIR}/include
DOC "The directory where GL/glew.h resides")
FIND_LIBRARY( GLEW_LIBRARY
NAMES GLEW glew
PATHS
/usr/lib64
/usr/lib
/usr/local/lib64
/usr/local/lib
/sw/lib
/opt/local/lib
${GLEW_ROOT_DIR}/lib
DOC "The GLEW library")
ENDIF (WIN32)
SET(GLEW_FOUND "NO")
IF (GLEW_INCLUDE_PATH AND GLEW_LIBRARY)
SET(GLEW_LIBRARIES ${GLEW_LIBRARY})
SET(GLEW_FOUND "YES")
ENDIF (GLEW_INCLUDE_PATH AND GLEW_LIBRARY)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(GLEW DEFAULT_MSG GLEW_LIBRARY GLEW_INCLUDE_PATH)

View file

@ -1,354 +1,354 @@
# This script locates the SFML library
# ------------------------------------
#
# Usage
# -----
#
# When you try to locate the SFML libraries, you must specify which modules you want to use (system, window, graphics, network, audio, main).
# If none is given, the SFML_LIBRARIES variable will be empty and you'll end up linking to nothing.
# example:
# find_package(SFML COMPONENTS graphics window system) // find the graphics, window and system modules
#
# You can enforce a specific version, either MAJOR.MINOR or only MAJOR.
# If nothing is specified, the version won't be checked (ie. any version will be accepted).
# example:
# find_package(SFML COMPONENTS ...) // no specific version required
# find_package(SFML 2 COMPONENTS ...) // any 2.x version
# find_package(SFML 2.4 COMPONENTS ...) // version 2.4 or greater
#
# By default, the dynamic libraries of SFML will be found. To find the static ones instead,
# you must set the SFML_STATIC_LIBRARIES variable to TRUE before calling find_package(SFML ...).
# Since you have to link yourself all the SFML dependencies when you link it statically, the following
# additional variables are defined: SFML_XXX_DEPENDENCIES and SFML_DEPENDENCIES (see their detailed
# description below).
# In case of static linking, the SFML_STATIC macro will also be defined by this script.
# example:
# set(SFML_STATIC_LIBRARIES TRUE)
# find_package(SFML 2 COMPONENTS network system)
#
# On Mac OS X if SFML_STATIC_LIBRARIES is not set to TRUE then by default CMake will search for frameworks unless
# CMAKE_FIND_FRAMEWORK is set to "NEVER" for example. Please refer to CMake documentation for more details.
# Moreover, keep in mind that SFML frameworks are only available as release libraries unlike dylibs which
# are available for both release and debug modes.
#
# If SFML is not installed in a standard path, you can use the SFML_ROOT CMake (or environment) variable
# to tell CMake where SFML is.
#
# Output
# ------
#
# This script defines the following variables:
# - For each specified module XXX (system, window, graphics, network, audio, main):
# - SFML_XXX_LIBRARY_DEBUG: the name of the debug library of the xxx module (set to SFML_XXX_LIBRARY_RELEASE is no debug version is found)
# - SFML_XXX_LIBRARY_RELEASE: the name of the release library of the xxx module (set to SFML_XXX_LIBRARY_DEBUG is no release version is found)
# - SFML_XXX_LIBRARY: the name of the library to link to for the xxx module (includes both debug and optimized names if necessary)
# - SFML_XXX_FOUND: true if either the debug or release library of the xxx module is found
# - SFML_XXX_DEPENDENCIES: the list of libraries the module depends on, in case of static linking
# - SFML_LIBRARIES: the list of all libraries corresponding to the required modules
# - SFML_FOUND: true if all the required modules are found
# - SFML_INCLUDE_DIR: the path where SFML headers are located (the directory containing the SFML/Config.hpp file)
# - SFML_DEPENDENCIES: the list of libraries SFML depends on, in case of static linking
#
# example:
# find_package(SFML 2 COMPONENTS system window graphics audio REQUIRED)
# include_directories(${SFML_INCLUDE_DIR})
# add_executable(myapp ...)
# target_link_libraries(myapp ${SFML_LIBRARIES})
# define the SFML_STATIC macro if static build was chosen
if(SFML_STATIC_LIBRARIES)
add_definitions(-DSFML_STATIC)
endif()
# define the list of search paths for headers and libraries
set(FIND_SFML_PATHS
${SFML_ROOT}
$ENV{SFML_ROOT}
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt)
# find the SFML include directory
find_path(SFML_INCLUDE_DIR SFML/Config.hpp
PATH_SUFFIXES include
PATHS ${FIND_SFML_PATHS})
# check the version number
set(SFML_VERSION_OK TRUE)
if(SFML_FIND_VERSION AND SFML_INCLUDE_DIR)
# extract the major and minor version numbers from SFML/Config.hpp
# we have to handle framework a little bit differently :
if("${SFML_INCLUDE_DIR}" MATCHES "SFML.framework")
set(SFML_CONFIG_HPP_INPUT "${SFML_INCLUDE_DIR}/Headers/Config.hpp")
else()
set(SFML_CONFIG_HPP_INPUT "${SFML_INCLUDE_DIR}/SFML/Config.hpp")
endif()
FILE(READ "${SFML_CONFIG_HPP_INPUT}" SFML_CONFIG_HPP_CONTENTS)
STRING(REGEX MATCH ".*#define SFML_VERSION_MAJOR ([0-9]+).*#define SFML_VERSION_MINOR ([0-9]+).*" SFML_CONFIG_HPP_CONTENTS "${SFML_CONFIG_HPP_CONTENTS}")
STRING(REGEX REPLACE ".*#define SFML_VERSION_MAJOR ([0-9]+).*" "\\1" SFML_VERSION_MAJOR "${SFML_CONFIG_HPP_CONTENTS}")
STRING(REGEX REPLACE ".*#define SFML_VERSION_MINOR ([0-9]+).*" "\\1" SFML_VERSION_MINOR "${SFML_CONFIG_HPP_CONTENTS}")
math(EXPR SFML_REQUESTED_VERSION "${SFML_FIND_VERSION_MAJOR} * 10 + ${SFML_FIND_VERSION_MINOR}")
# if we could extract them, compare with the requested version number
if (SFML_VERSION_MAJOR)
# transform version numbers to an integer
math(EXPR SFML_VERSION "${SFML_VERSION_MAJOR} * 10 + ${SFML_VERSION_MINOR}")
# compare them
if(SFML_VERSION LESS SFML_REQUESTED_VERSION)
set(SFML_VERSION_OK FALSE)
endif()
else()
# SFML version is < 2.0
if (SFML_REQUESTED_VERSION GREATER 19)
set(SFML_VERSION_OK FALSE)
set(SFML_VERSION_MAJOR 1)
set(SFML_VERSION_MINOR x)
endif()
endif()
endif()
# find the requested modules
set(SFML_FOUND TRUE) # will be set to false if one of the required modules is not found
foreach(FIND_SFML_COMPONENT ${SFML_FIND_COMPONENTS})
string(TOLOWER ${FIND_SFML_COMPONENT} FIND_SFML_COMPONENT_LOWER)
string(TOUPPER ${FIND_SFML_COMPONENT} FIND_SFML_COMPONENT_UPPER)
set(FIND_SFML_COMPONENT_NAME sfml-${FIND_SFML_COMPONENT_LOWER})
# no suffix for sfml-main, it is always a static library
if(FIND_SFML_COMPONENT_LOWER STREQUAL "main")
# release library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE
NAMES ${FIND_SFML_COMPONENT_NAME}
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# debug library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG
NAMES ${FIND_SFML_COMPONENT_NAME}-d
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
else()
# static release library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE
NAMES ${FIND_SFML_COMPONENT_NAME}-s
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# static debug library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG
NAMES ${FIND_SFML_COMPONENT_NAME}-s-d
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# dynamic release library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE
NAMES ${FIND_SFML_COMPONENT_NAME}
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# dynamic debug library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG
NAMES ${FIND_SFML_COMPONENT_NAME}-d
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# choose the entries that fit the requested link type
if(SFML_STATIC_LIBRARIES)
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE})
endif()
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG})
endif()
else()
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE})
endif()
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG})
endif()
endif()
endif()
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG OR SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE)
# library found
set(SFML_${FIND_SFML_COMPONENT_UPPER}_FOUND TRUE)
# if both are found, set SFML_XXX_LIBRARY to contain both
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG AND SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY debug ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG}
optimized ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE})
endif()
# if only one debug/release variant is found, set the other to be equal to the found one
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG AND NOT SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE)
# debug and not release
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG})
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG})
endif()
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE AND NOT SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG)
# release and not debug
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE})
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE})
endif()
else()
# library not found
set(SFML_FOUND FALSE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_FOUND FALSE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY "")
set(FIND_SFML_MISSING "${FIND_SFML_MISSING} SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY")
endif()
# mark as advanced
MARK_AS_ADVANCED(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG)
# add to the global list of libraries
set(SFML_LIBRARIES ${SFML_LIBRARIES} "${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY}")
endforeach()
# in case of static linking, we must also define the list of all the dependencies of SFML libraries
if(SFML_STATIC_LIBRARIES)
# detect the OS
if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
set(FIND_SFML_OS_WINDOWS 1)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
set(FIND_SFML_OS_LINUX 1)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
set(FIND_SFML_OS_FREEBSD 1)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
set(FIND_SFML_OS_MACOSX 1)
endif()
# start with an empty list
set(SFML_DEPENDENCIES)
set(FIND_SFML_DEPENDENCIES_NOTFOUND)
# macro that searches for a 3rd-party library
macro(find_sfml_dependency output friendlyname)
find_library(${output} NAMES ${ARGN} PATHS ${FIND_SFML_PATHS} PATH_SUFFIXES lib)
if(${${output}} STREQUAL "${output}-NOTFOUND")
unset(output)
set(FIND_SFML_DEPENDENCIES_NOTFOUND "${FIND_SFML_DEPENDENCIES_NOTFOUND} ${friendlyname}")
endif()
endmacro()
# sfml-system
list(FIND SFML_FIND_COMPONENTS "system" FIND_SFML_SYSTEM_COMPONENT)
if(NOT ${FIND_SFML_SYSTEM_COMPONENT} EQUAL -1)
# update the list -- these are only system libraries, no need to find them
if(FIND_SFML_OS_LINUX OR FIND_SFML_OS_FREEBSD OR FIND_SFML_OS_MACOSX)
set(SFML_SYSTEM_DEPENDENCIES "pthread")
endif()
if(FIND_SFML_OS_LINUX)
set(SFML_SYSTEM_DEPENDENCIES "rt")
endif()
if(FIND_SFML_OS_WINDOWS)
set(SFML_SYSTEM_DEPENDENCIES "winmm")
endif()
set(SFML_DEPENDENCIES ${SFML_SYSTEM_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-network
list(FIND SFML_FIND_COMPONENTS "network" FIND_SFML_NETWORK_COMPONENT)
if(NOT ${FIND_SFML_NETWORK_COMPONENT} EQUAL -1)
# update the list -- these are only system libraries, no need to find them
if(FIND_SFML_OS_WINDOWS)
set(SFML_NETWORK_DEPENDENCIES "ws2_32")
endif()
set(SFML_DEPENDENCIES ${SFML_NETWORK_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-window
list(FIND SFML_FIND_COMPONENTS "window" FIND_SFML_WINDOW_COMPONENT)
if(NOT ${FIND_SFML_WINDOW_COMPONENT} EQUAL -1)
# find libraries
if(FIND_SFML_OS_LINUX)
find_sfml_dependency(X11_LIBRARY "X11" X11)
find_sfml_dependency(XRANDR_LIBRARY "Xrandr" Xrandr)
endif()
# update the list
if(FIND_SFML_OS_WINDOWS)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "opengl32" "winmm" "gdi32")
elseif(FIND_SFML_OS_LINUX OR FIND_SFML_OS_FREEBSD)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "GL" ${X11_LIBRARY} ${XRANDR_LIBRARY})
if(FIND_SFML_OS_FREEBSD)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "usbhid")
endif()
elseif(FIND_SFML_OS_MACOSX)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "-framework OpenGL -framework Foundation -framework AppKit -framework IOKit -framework Carbon")
endif()
set(SFML_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-graphics
list(FIND SFML_FIND_COMPONENTS "graphics" FIND_SFML_GRAPHICS_COMPONENT)
if(NOT ${FIND_SFML_GRAPHICS_COMPONENT} EQUAL -1)
# find libraries
find_sfml_dependency(FREETYPE_LIBRARY "FreeType" freetype)
find_sfml_dependency(GLEW_LIBRARY "GLEW" glew GLEW glew32 glew32s glew64 glew64s)
find_sfml_dependency(JPEG_LIBRARY "libjpeg" jpeg)
# update the list
set(SFML_GRAPHICS_DEPENDENCIES ${FREETYPE_LIBRARY} ${GLEW_LIBRARY} ${JPEG_LIBRARY})
set(SFML_DEPENDENCIES ${SFML_GRAPHICS_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-audio
list(FIND SFML_FIND_COMPONENTS "audio" FIND_SFML_AUDIO_COMPONENT)
if(NOT ${FIND_SFML_AUDIO_COMPONENT} EQUAL -1)
# find libraries
find_sfml_dependency(OPENAL_LIBRARY "OpenAL" openal openal32)
find_sfml_dependency(SNDFILE_LIBRARY "libsndfile" sndfile)
# update the list
set(SFML_AUDIO_DEPENDENCIES ${OPENAL_LIBRARY} ${SNDFILE_LIBRARY})
set(SFML_DEPENDENCIES ${SFML_AUDIO_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
endif()
# handle errors
if(NOT SFML_VERSION_OK)
# SFML version not ok
set(FIND_SFML_ERROR "SFML found but version too low (requested: ${SFML_FIND_VERSION}, found: ${SFML_VERSION_MAJOR}.${SFML_VERSION_MINOR})")
set(SFML_FOUND FALSE)
elseif(SFML_STATIC_LIBRARIES AND FIND_SFML_DEPENDENCIES_NOTFOUND)
set(FIND_SFML_ERROR "SFML found but some of its dependencies are missing (${FIND_SFML_DEPENDENCIES_NOTFOUND})")
set(SFML_FOUND FALSE)
elseif(NOT SFML_FOUND)
# include directory or library not found
set(FIND_SFML_ERROR "Could NOT find SFML (missing: ${FIND_SFML_MISSING})")
endif()
if (NOT SFML_FOUND)
if(SFML_FIND_REQUIRED)
# fatal error
message(FATAL_ERROR ${FIND_SFML_ERROR})
elseif(NOT SFML_FIND_QUIETLY)
# error but continue
message("${FIND_SFML_ERROR}")
endif()
endif()
# handle success
if(SFML_FOUND)
message(STATUS "Found SFML ${SFML_VERSION_MAJOR}.${SFML_VERSION_MINOR} in ${SFML_INCLUDE_DIR}")
endif()
# This script locates the SFML library
# ------------------------------------
#
# Usage
# -----
#
# When you try to locate the SFML libraries, you must specify which modules you want to use (system, window, graphics, network, audio, main).
# If none is given, the SFML_LIBRARIES variable will be empty and you'll end up linking to nothing.
# example:
# find_package(SFML COMPONENTS graphics window system) // find the graphics, window and system modules
#
# You can enforce a specific version, either MAJOR.MINOR or only MAJOR.
# If nothing is specified, the version won't be checked (ie. any version will be accepted).
# example:
# find_package(SFML COMPONENTS ...) // no specific version required
# find_package(SFML 2 COMPONENTS ...) // any 2.x version
# find_package(SFML 2.4 COMPONENTS ...) // version 2.4 or greater
#
# By default, the dynamic libraries of SFML will be found. To find the static ones instead,
# you must set the SFML_STATIC_LIBRARIES variable to TRUE before calling find_package(SFML ...).
# Since you have to link yourself all the SFML dependencies when you link it statically, the following
# additional variables are defined: SFML_XXX_DEPENDENCIES and SFML_DEPENDENCIES (see their detailed
# description below).
# In case of static linking, the SFML_STATIC macro will also be defined by this script.
# example:
# set(SFML_STATIC_LIBRARIES TRUE)
# find_package(SFML 2 COMPONENTS network system)
#
# On Mac OS X if SFML_STATIC_LIBRARIES is not set to TRUE then by default CMake will search for frameworks unless
# CMAKE_FIND_FRAMEWORK is set to "NEVER" for example. Please refer to CMake documentation for more details.
# Moreover, keep in mind that SFML frameworks are only available as release libraries unlike dylibs which
# are available for both release and debug modes.
#
# If SFML is not installed in a standard path, you can use the SFML_ROOT CMake (or environment) variable
# to tell CMake where SFML is.
#
# Output
# ------
#
# This script defines the following variables:
# - For each specified module XXX (system, window, graphics, network, audio, main):
# - SFML_XXX_LIBRARY_DEBUG: the name of the debug library of the xxx module (set to SFML_XXX_LIBRARY_RELEASE is no debug version is found)
# - SFML_XXX_LIBRARY_RELEASE: the name of the release library of the xxx module (set to SFML_XXX_LIBRARY_DEBUG is no release version is found)
# - SFML_XXX_LIBRARY: the name of the library to link to for the xxx module (includes both debug and optimized names if necessary)
# - SFML_XXX_FOUND: true if either the debug or release library of the xxx module is found
# - SFML_XXX_DEPENDENCIES: the list of libraries the module depends on, in case of static linking
# - SFML_LIBRARIES: the list of all libraries corresponding to the required modules
# - SFML_FOUND: true if all the required modules are found
# - SFML_INCLUDE_DIR: the path where SFML headers are located (the directory containing the SFML/Config.hpp file)
# - SFML_DEPENDENCIES: the list of libraries SFML depends on, in case of static linking
#
# example:
# find_package(SFML 2 COMPONENTS system window graphics audio REQUIRED)
# include_directories(${SFML_INCLUDE_DIR})
# add_executable(myapp ...)
# target_link_libraries(myapp ${SFML_LIBRARIES})
# define the SFML_STATIC macro if static build was chosen
if(SFML_STATIC_LIBRARIES)
add_definitions(-DSFML_STATIC)
endif()
# define the list of search paths for headers and libraries
set(FIND_SFML_PATHS
${SFML_ROOT}
$ENV{SFML_ROOT}
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt)
# find the SFML include directory
find_path(SFML_INCLUDE_DIR SFML/Config.hpp
PATH_SUFFIXES include
PATHS ${FIND_SFML_PATHS})
# check the version number
set(SFML_VERSION_OK TRUE)
if(SFML_FIND_VERSION AND SFML_INCLUDE_DIR)
# extract the major and minor version numbers from SFML/Config.hpp
# we have to handle framework a little bit differently:
if("${SFML_INCLUDE_DIR}" MATCHES "SFML.framework")
set(SFML_CONFIG_HPP_INPUT "${SFML_INCLUDE_DIR}/Headers/Config.hpp")
else()
set(SFML_CONFIG_HPP_INPUT "${SFML_INCLUDE_DIR}/SFML/Config.hpp")
endif()
FILE(READ "${SFML_CONFIG_HPP_INPUT}" SFML_CONFIG_HPP_CONTENTS)
STRING(REGEX MATCH ".*#define SFML_VERSION_MAJOR ([0-9]+).*#define SFML_VERSION_MINOR ([0-9]+).*" SFML_CONFIG_HPP_CONTENTS "${SFML_CONFIG_HPP_CONTENTS}")
STRING(REGEX REPLACE ".*#define SFML_VERSION_MAJOR ([0-9]+).*" "\\1" SFML_VERSION_MAJOR "${SFML_CONFIG_HPP_CONTENTS}")
STRING(REGEX REPLACE ".*#define SFML_VERSION_MINOR ([0-9]+).*" "\\1" SFML_VERSION_MINOR "${SFML_CONFIG_HPP_CONTENTS}")
math(EXPR SFML_REQUESTED_VERSION "${SFML_FIND_VERSION_MAJOR} * 10 + ${SFML_FIND_VERSION_MINOR}")
# if we could extract them, compare with the requested version number
if (SFML_VERSION_MAJOR)
# transform version numbers to an integer
math(EXPR SFML_VERSION "${SFML_VERSION_MAJOR} * 10 + ${SFML_VERSION_MINOR}")
# compare them
if(SFML_VERSION LESS SFML_REQUESTED_VERSION)
set(SFML_VERSION_OK FALSE)
endif()
else()
# SFML version is < 2.0
if (SFML_REQUESTED_VERSION GREATER 19)
set(SFML_VERSION_OK FALSE)
set(SFML_VERSION_MAJOR 1)
set(SFML_VERSION_MINOR x)
endif()
endif()
endif()
# find the requested modules
set(SFML_FOUND TRUE) # will be set to false if one of the required modules is not found
foreach(FIND_SFML_COMPONENT ${SFML_FIND_COMPONENTS})
string(TOLOWER ${FIND_SFML_COMPONENT} FIND_SFML_COMPONENT_LOWER)
string(TOUPPER ${FIND_SFML_COMPONENT} FIND_SFML_COMPONENT_UPPER)
set(FIND_SFML_COMPONENT_NAME sfml-${FIND_SFML_COMPONENT_LOWER})
# no suffix for sfml-main, it is always a static library
if(FIND_SFML_COMPONENT_LOWER STREQUAL "main")
# release library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE
NAMES ${FIND_SFML_COMPONENT_NAME}
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# debug library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG
NAMES ${FIND_SFML_COMPONENT_NAME}-d
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
else()
# static release library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE
NAMES ${FIND_SFML_COMPONENT_NAME}-s
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# static debug library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG
NAMES ${FIND_SFML_COMPONENT_NAME}-s-d
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# dynamic release library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE
NAMES ${FIND_SFML_COMPONENT_NAME}
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# dynamic debug library
find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG
NAMES ${FIND_SFML_COMPONENT_NAME}-d
PATH_SUFFIXES lib64 lib
PATHS ${FIND_SFML_PATHS})
# choose the entries that fit the requested link type
if(SFML_STATIC_LIBRARIES)
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE})
endif()
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG})
endif()
else()
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE})
endif()
if(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG})
endif()
endif()
endif()
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG OR SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE)
# library found
set(SFML_${FIND_SFML_COMPONENT_UPPER}_FOUND TRUE)
# if both are found, set SFML_XXX_LIBRARY to contain both
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG AND SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY debug ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG}
optimized ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE})
endif()
# if only one debug/release variant is found, set the other to be equal to the found one
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG AND NOT SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE)
# debug and not release
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG})
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG})
endif()
if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE AND NOT SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG)
# release and not debug
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE})
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE})
endif()
else()
# library not found
set(SFML_FOUND FALSE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_FOUND FALSE)
set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY "")
set(FIND_SFML_MISSING "${FIND_SFML_MISSING} SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY")
endif()
# mark as advanced
MARK_AS_ADVANCED(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_RELEASE
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_STATIC_DEBUG
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_RELEASE
SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DYNAMIC_DEBUG)
# add to the global list of libraries
set(SFML_LIBRARIES ${SFML_LIBRARIES} "${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY}")
endforeach()
# in case of static linking, we must also define the list of all the dependencies of SFML libraries
if(SFML_STATIC_LIBRARIES)
# detect the OS
if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
set(FIND_SFML_OS_WINDOWS 1)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
set(FIND_SFML_OS_LINUX 1)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
set(FIND_SFML_OS_FREEBSD 1)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
set(FIND_SFML_OS_MACOSX 1)
endif()
# start with an empty list
set(SFML_DEPENDENCIES)
set(FIND_SFML_DEPENDENCIES_NOTFOUND)
# macro that searches for a 3rd-party library
macro(find_sfml_dependency output friendlyname)
find_library(${output} NAMES ${ARGN} PATHS ${FIND_SFML_PATHS} PATH_SUFFIXES lib)
if(${${output}} STREQUAL "${output}-NOTFOUND")
unset(output)
set(FIND_SFML_DEPENDENCIES_NOTFOUND "${FIND_SFML_DEPENDENCIES_NOTFOUND} ${friendlyname}")
endif()
endmacro()
# sfml-system
list(FIND SFML_FIND_COMPONENTS "system" FIND_SFML_SYSTEM_COMPONENT)
if(NOT ${FIND_SFML_SYSTEM_COMPONENT} EQUAL -1)
# update the list -- these are only system libraries, no need to find them
if(FIND_SFML_OS_LINUX OR FIND_SFML_OS_FREEBSD OR FIND_SFML_OS_MACOSX)
set(SFML_SYSTEM_DEPENDENCIES "pthread")
endif()
if(FIND_SFML_OS_LINUX)
set(SFML_SYSTEM_DEPENDENCIES "rt")
endif()
if(FIND_SFML_OS_WINDOWS)
set(SFML_SYSTEM_DEPENDENCIES "winmm")
endif()
set(SFML_DEPENDENCIES ${SFML_SYSTEM_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-network
list(FIND SFML_FIND_COMPONENTS "network" FIND_SFML_NETWORK_COMPONENT)
if(NOT ${FIND_SFML_NETWORK_COMPONENT} EQUAL -1)
# update the list -- these are only system libraries, no need to find them
if(FIND_SFML_OS_WINDOWS)
set(SFML_NETWORK_DEPENDENCIES "ws2_32")
endif()
set(SFML_DEPENDENCIES ${SFML_NETWORK_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-window
list(FIND SFML_FIND_COMPONENTS "window" FIND_SFML_WINDOW_COMPONENT)
if(NOT ${FIND_SFML_WINDOW_COMPONENT} EQUAL -1)
# find libraries
if(FIND_SFML_OS_LINUX)
find_sfml_dependency(X11_LIBRARY "X11" X11)
find_sfml_dependency(XRANDR_LIBRARY "Xrandr" Xrandr)
endif()
# update the list
if(FIND_SFML_OS_WINDOWS)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "opengl32" "winmm" "gdi32")
elseif(FIND_SFML_OS_LINUX OR FIND_SFML_OS_FREEBSD)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "GL" ${X11_LIBRARY} ${XRANDR_LIBRARY})
if(FIND_SFML_OS_FREEBSD)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "usbhid")
endif()
elseif(FIND_SFML_OS_MACOSX)
set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "-framework OpenGL -framework Foundation -framework AppKit -framework IOKit -framework Carbon")
endif()
set(SFML_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-graphics
list(FIND SFML_FIND_COMPONENTS "graphics" FIND_SFML_GRAPHICS_COMPONENT)
if(NOT ${FIND_SFML_GRAPHICS_COMPONENT} EQUAL -1)
# find libraries
find_sfml_dependency(FREETYPE_LIBRARY "FreeType" freetype)
find_sfml_dependency(GLEW_LIBRARY "GLEW" glew GLEW glew32 glew32s glew64 glew64s)
find_sfml_dependency(JPEG_LIBRARY "libjpeg" jpeg)
# update the list
set(SFML_GRAPHICS_DEPENDENCIES ${FREETYPE_LIBRARY} ${GLEW_LIBRARY} ${JPEG_LIBRARY})
set(SFML_DEPENDENCIES ${SFML_GRAPHICS_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
# sfml-audio
list(FIND SFML_FIND_COMPONENTS "audio" FIND_SFML_AUDIO_COMPONENT)
if(NOT ${FIND_SFML_AUDIO_COMPONENT} EQUAL -1)
# find libraries
find_sfml_dependency(OPENAL_LIBRARY "OpenAL" openal openal32)
find_sfml_dependency(SNDFILE_LIBRARY "libsndfile" sndfile)
# update the list
set(SFML_AUDIO_DEPENDENCIES ${OPENAL_LIBRARY} ${SNDFILE_LIBRARY})
set(SFML_DEPENDENCIES ${SFML_AUDIO_DEPENDENCIES} ${SFML_DEPENDENCIES})
endif()
endif()
# handle errors
if(NOT SFML_VERSION_OK)
# SFML version not ok
set(FIND_SFML_ERROR "SFML found but version too low (requested: ${SFML_FIND_VERSION}, found: ${SFML_VERSION_MAJOR}.${SFML_VERSION_MINOR})")
set(SFML_FOUND FALSE)
elseif(SFML_STATIC_LIBRARIES AND FIND_SFML_DEPENDENCIES_NOTFOUND)
set(FIND_SFML_ERROR "SFML found but some of its dependencies are missing (${FIND_SFML_DEPENDENCIES_NOTFOUND})")
set(SFML_FOUND FALSE)
elseif(NOT SFML_FOUND)
# include directory or library not found
set(FIND_SFML_ERROR "Could NOT find SFML (missing: ${FIND_SFML_MISSING})")
endif()
if (NOT SFML_FOUND)
if(SFML_FIND_REQUIRED)
# fatal error
message(FATAL_ERROR ${FIND_SFML_ERROR})
elseif(NOT SFML_FIND_QUIETLY)
# error but continue
message("${FIND_SFML_ERROR}")
endif()
endif()
# handle success
if(SFML_FOUND)
message(STATUS "Found SFML ${SFML_VERSION_MAJOR}.${SFML_VERSION_MINOR} in ${SFML_INCLUDE_DIR}")
endif()

View file

@ -1,28 +1,28 @@
# - Find sndfile
# Find the native sndfile includes and libraries
#
# SNDFILE_INCLUDE_DIR - where to find sndfile.h, etc.
# SNDFILE_LIBRARIES - List of libraries when using libsndfile.
# SNDFILE_FOUND - True if libsndfile found.
if(SNDFILE_INCLUDE_DIR)
# Already in cache, be silent
set(SNDFILE_FIND_QUIETLY TRUE)
endif(SNDFILE_INCLUDE_DIR)
find_path(SNDFILE_INCLUDE_DIR sndfile.h)
find_library(SNDFILE_LIBRARY NAMES sndfile sndfile-1)
# Handle the QUIETLY and REQUIRED arguments and set SNDFILE_FOUND to TRUE if
# all listed variables are TRUE.
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(SNDFILE DEFAULT_MSG SNDFILE_LIBRARY SNDFILE_INCLUDE_DIR)
if(SNDFILE_FOUND)
set(SNDFILE_LIBRARIES ${SNDFILE_LIBRARY})
else(SNDFILE_FOUND)
set(SNDFILE_LIBRARIES)
endif(SNDFILE_FOUND)
mark_as_advanced(SNDFILE_INCLUDE_DIR SNDFILE_LIBRARY)
# - Find sndfile
# Find the native sndfile includes and libraries
#
# SNDFILE_INCLUDE_DIR - where to find sndfile.h, etc.
# SNDFILE_LIBRARIES - List of libraries when using libsndfile.
# SNDFILE_FOUND - True if libsndfile found.
if(SNDFILE_INCLUDE_DIR)
# Already in cache, be silent
set(SNDFILE_FIND_QUIETLY TRUE)
endif(SNDFILE_INCLUDE_DIR)
find_path(SNDFILE_INCLUDE_DIR sndfile.h)
find_library(SNDFILE_LIBRARY NAMES sndfile sndfile-1)
# Handle the QUIETLY and REQUIRED arguments and set SNDFILE_FOUND to TRUE if
# all listed variables are TRUE.
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(SNDFILE DEFAULT_MSG SNDFILE_LIBRARY SNDFILE_INCLUDE_DIR)
if(SNDFILE_FOUND)
set(SNDFILE_LIBRARIES ${SNDFILE_LIBRARY})
else(SNDFILE_FOUND)
set(SNDFILE_LIBRARIES)
endif(SNDFILE_FOUND)
mark_as_advanced(SNDFILE_INCLUDE_DIR SNDFILE_LIBRARY)

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,9 @@
</div>
<div id="footer-container">
<div id="footer">
Copyright © Laurent Gomila &nbsp;::&nbsp;
Documentation generated by <a href="http://www.doxygen.org/" title="doxygen website">doxygen</a> &nbsp;::&nbsp;
</div>
</div>
</body>
</html>
</div>
<div id="footer-container">
<div id="footer">
Copyright © Laurent Gomila &nbsp;::&nbsp;
Documentation generated by <a href="http://www.doxygen.org/" title="doxygen website">doxygen</a> &nbsp;::&nbsp;
</div>
</div>
</body>
</html>

View file

@ -1,15 +1,15 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SFML - Simple and Fast Multimedia Library</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<!--<link rel='stylesheet' type='text/css' href="http://fonts.googleapis.com/css?family=Ubuntu:400,700,400italic"/>-->
<link rel="stylesheet" type="text/css" href="doxygen.css" title="default" media="screen,print" />
</head>
<body>
<div id="banner-container">
<div id="banner">
<span id="sfml">SFML</span>
</div>
</div>
<div id="content">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SFML - Simple and Fast Multimedia Library</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<!--<link rel='stylesheet' type='text/css' href="http://fonts.googleapis.com/css?family=Ubuntu:400,700,400italic"/>-->
<link rel="stylesheet" type="text/css" href="doxygen.css" title="default" media="screen,print" />
</head>
<body>
<div id="banner-container">
<div id="banner">
<span id="sfml">SFML</span>
</div>
</div>
<div id="content">

View file

@ -1,71 +1,71 @@
////////////////////////////////////////////////////////////
/// \mainpage
///
/// \section welcome Welcome
/// Welcome to the official SFML documentation. Here you will find a detailed
/// view of all the SFML <a href="./annotated.php">classes</a> and functions. <br/>
/// If you are looking for tutorials, you can visit the official website
/// at <a href="http://www.sfml-dev.org/">www.sfml-dev.org</a>.
///
/// \section example Short example
/// Here is a short example, to show you how simple it is to use SFML :
///
/// \code
///
/// #include <SFML/Audio.hpp>
/// #include <SFML/Graphics.hpp>
///
/// int main()
/// {
/// // Create the main window
/// sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
///
/// // Load a sprite to display
/// sf::Texture texture;
/// if (!texture.loadFromFile("cute_image.jpg"))
/// return EXIT_FAILURE;
/// sf::Sprite sprite(texture);
///
/// // Create a graphical text to display
/// sf::Font font;
/// if (!font.loadFromFile("arial.ttf"))
/// return EXIT_FAILURE;
/// sf::Text text("Hello SFML", font, 50);
///
/// // Load a music to play
/// sf::Music music;
/// if (!music.openFromFile("nice_music.ogg"))
/// return EXIT_FAILURE;
///
/// // Play the music
/// music.play();
///
/// // Start the game loop
/// while (window.isOpen())
/// {
/// // Process events
/// sf::Event event;
/// while (window.pollEvent(event))
/// {
/// // Close window : exit
/// if (event.type == sf::Event::Closed)
/// window.close();
/// }
///
/// // Clear screen
/// window.clear();
///
/// // Draw the sprite
/// window.draw(sprite);
///
/// // Draw the string
/// window.draw(text);
///
/// // Update the window
/// window.display();
/// }
///
/// return EXIT_SUCCESS;
/// }
/// \endcode
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
/// \mainpage
///
/// \section welcome Welcome
/// Welcome to the official SFML documentation. Here you will find a detailed
/// view of all the SFML <a href="./annotated.php">classes</a> and functions. <br/>
/// If you are looking for tutorials, you can visit the official website
/// at <a href="http://www.sfml-dev.org/">www.sfml-dev.org</a>.
///
/// \section example Short example
/// Here is a short example, to show you how simple it is to use SFML:
///
/// \code
///
/// #include <SFML/Audio.hpp>
/// #include <SFML/Graphics.hpp>
///
/// int main()
/// {
/// // Create the main window
/// sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
///
/// // Load a sprite to display
/// sf::Texture texture;
/// if (!texture.loadFromFile("cute_image.jpg"))
/// return EXIT_FAILURE;
/// sf::Sprite sprite(texture);
///
/// // Create a graphical text to display
/// sf::Font font;
/// if (!font.loadFromFile("arial.ttf"))
/// return EXIT_FAILURE;
/// sf::Text text("Hello SFML", font, 50);
///
/// // Load a music to play
/// sf::Music music;
/// if (!music.openFromFile("nice_music.ogg"))
/// return EXIT_FAILURE;
///
/// // Play the music
/// music.play();
///
/// // Start the game loop
/// while (window.isOpen())
/// {
/// // Process events
/// sf::Event event;
/// while (window.pollEvent(event))
/// {
/// // Close window: exit
/// if (event.type == sf::Event::Closed)
/// window.close();
/// }
///
/// // Clear screen
/// window.clear();
///
/// // Draw the sprite
/// window.draw(sprite);
///
/// // Draw the string
/// window.draw(text);
///
/// // Update the window
/// window.display();
/// }
///
/// return EXIT_SUCCESS;
/// }
/// \endcode
////////////////////////////////////////////////////////////

View file

@ -1,18 +1,18 @@
# add the examples subdirectories
add_subdirectory(ftp)
add_subdirectory(opengl)
add_subdirectory(pong)
add_subdirectory(shader)
add_subdirectory(sockets)
add_subdirectory(sound)
add_subdirectory(sound_capture)
add_subdirectory(voip)
add_subdirectory(window)
if(SFML_OS_WINDOWS)
add_subdirectory(win32)
elseif(SFML_OS_LINUX OR SFML_OS_FREEBSD)
add_subdirectory(ftp)
add_subdirectory(opengl)
add_subdirectory(pong)
add_subdirectory(shader)
add_subdirectory(sockets)
add_subdirectory(sound)
add_subdirectory(sound_capture)
add_subdirectory(voip)
add_subdirectory(window)
if(SFML_OS_WINDOWS)
add_subdirectory(win32)
elseif(SFML_OS_LINUX OR SFML_OS_FREEBSD)
add_subdirectory(X11)
elseif(SFML_OS_MACOSX)
add_subdirectory(cocoa)
endif()
elseif(SFML_OS_MACOSX)
add_subdirectory(cocoa)
endif()

View file

@ -1,16 +1,16 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/X11)
# all source files
set(SRC ${SRCROOT}/X11.cpp)
# find OpenGL, GLU and X11
find_package(OpenGL REQUIRED)
include_directories(${OPENGL_INCLUDE_DIR})
find_package(X11 REQUIRED)
include_directories(${X11_INCLUDE_DIR})
# define the X11 target
sfml_add_example(X11 GUI_APP
SOURCES ${SRC}
DEPENDS sfml-window sfml-system ${OPENGL_LIBRARIES} ${X11_LIBRARIES})
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/X11)
# all source files
set(SRC ${SRCROOT}/X11.cpp)
# find OpenGL, GLU and X11
find_package(OpenGL REQUIRED)
include_directories(${OPENGL_INCLUDE_DIR})
find_package(X11 REQUIRED)
include_directories(${X11_INCLUDE_DIR})
# define the X11 target
sfml_add_example(X11 GUI_APP
SOURCES ${SRC}
DEPENDS sfml-window sfml-system ${OPENGL_LIBRARIES} ${X11_LIBRARIES})

View file

@ -1,199 +1,199 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window.hpp>
#include <X11/Xlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <iostream>
////////////////////////////////////////////////////////////
/// Initialize OpenGL states into the specified view
///
/// \param Window Target window to initialize
///
////////////////////////////////////////////////////////////
void initialize(sf::Window& window)
{
// Activate the window
window.setActive();
// Setup OpenGL states
// Set color and depth clear value
glClearDepth(1.f);
glClearColor(0.f, 0.5f, 0.5f, 0.f);
// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.f, 1.f, 1.f, 500.f);
}
////////////////////////////////////////////////////////////
/// Draw the OpenGL scene (a rotating cube) into
/// the specified view
///
/// \param window Target window for rendering
/// \param elapsedTime Time elapsed since the last draw
///
////////////////////////////////////////////////////////////
void draw(sf::Window& window, float elapsedTime)
{
// Activate the window
window.setActive();
// Clear color and depth buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Apply some transformations
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.f, 0.f, -200.f);
glRotatef(elapsedTime * 0.05f, 1.f, 0.f, 0.f);
glRotatef(elapsedTime * 0.03f, 0.f, 1.f, 0.f);
glRotatef(elapsedTime * 0.09f, 0.f, 0.f, 1.f);
// Draw a cube
glBegin(GL_QUADS);
glColor3f(1.f, 1.f, 0.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, -50.f);
glVertex3f( 50.f, -50.f, -50.f);
glColor3f(1.f, 1.f, 0.f);
glVertex3f(-50.f, -50.f, 50.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f( 50.f, 50.f, 50.f);
glVertex3f( 50.f, -50.f, 50.f);
glColor3f(0.f, 1.f, 1.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f(-50.f, -50.f, 50.f);
glColor3f(0.f, 1.f, 1.f);
glVertex3f(50.f, -50.f, -50.f);
glVertex3f(50.f, 50.f, -50.f);
glVertex3f(50.f, 50.f, 50.f);
glVertex3f(50.f, -50.f, 50.f);
glColor3f(1.f, 0.f, 1.f);
glVertex3f(-50.f, -50.f, 50.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f( 50.f, -50.f, -50.f);
glVertex3f( 50.f, -50.f, 50.f);
glColor3f(1.f, 0.f, 1.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, 50.f);
glEnd();
}
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Error code
///
////////////////////////////////////////////////////////////
int main()
{
// Open a connection with the X server
Display* display = XOpenDisplay(NULL);
if (!display)
return EXIT_FAILURE;
// Get the default screen
int screen = DefaultScreen(display);
// Let's create the main window
XSetWindowAttributes attributes;
attributes.background_pixel = BlackPixel(display, screen);
attributes.event_mask = KeyPressMask;
Window window = XCreateWindow(display, RootWindow(display, screen),
0, 0, 650, 330, 0,
DefaultDepth(display, screen),
InputOutput,
DefaultVisual(display, screen),
CWBackPixel | CWEventMask, &attributes);
if (!window)
return EXIT_FAILURE;
// Set the window's name
XStoreName(display, window , "SFML Window");
// Let's create the windows which will serve as containers for our SFML views
Window view1 = XCreateWindow(display, window,
10, 10, 310, 310, 0,
DefaultDepth(display, screen),
InputOutput,
DefaultVisual(display, screen),
0, NULL);
Window view2 = XCreateWindow(display, window,
330, 10, 310, 310, 0,
DefaultDepth(display, screen),
InputOutput,
DefaultVisual(display, screen),
0, NULL);
// Show our windows
XMapWindow(display, window);
XFlush(display);
// Create our SFML views
sf::Window SFMLView1(view1);
sf::Window SFMLView2(view2);
// Create a clock for measuring elapsed time
sf::Clock clock;
// Initialize our views
initialize(SFMLView1);
initialize(SFMLView2);
// Start the event loop
bool running = true;
while (running)
{
while (XPending(display))
{
// Get the next pending event
XEvent event;
XNextEvent(display, &event);
// Process it
switch (event.type)
{
// Any key is pressed : quit
case KeyPress :
running = false;
break;
}
}
// Draw something into our views
draw(SFMLView1, clock.getElapsedTime().asSeconds());
draw(SFMLView2, clock.getElapsedTime().asSeconds() * 0.3f);
// Display the views on screen
SFMLView1.display();
SFMLView2.display();
}
// Close the display
XCloseDisplay(display);
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window.hpp>
#include <X11/Xlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <iostream>
////////////////////////////////////////////////////////////
/// Initialize OpenGL states into the specified view
///
/// \param Window Target window to initialize
///
////////////////////////////////////////////////////////////
void initialize(sf::Window& window)
{
// Activate the window
window.setActive();
// Setup OpenGL states
// Set color and depth clear value
glClearDepth(1.f);
glClearColor(0.f, 0.5f, 0.5f, 0.f);
// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.f, 1.f, 1.f, 500.f);
}
////////////////////////////////////////////////////////////
/// Draw the OpenGL scene (a rotating cube) into
/// the specified view
///
/// \param window Target window for rendering
/// \param elapsedTime Time elapsed since the last draw
///
////////////////////////////////////////////////////////////
void draw(sf::Window& window, float elapsedTime)
{
// Activate the window
window.setActive();
// Clear color and depth buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Apply some transformations
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.f, 0.f, -200.f);
glRotatef(elapsedTime * 0.05f, 1.f, 0.f, 0.f);
glRotatef(elapsedTime * 0.03f, 0.f, 1.f, 0.f);
glRotatef(elapsedTime * 0.09f, 0.f, 0.f, 1.f);
// Draw a cube
glBegin(GL_QUADS);
glColor3f(1.f, 1.f, 0.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, -50.f);
glVertex3f( 50.f, -50.f, -50.f);
glColor3f(1.f, 1.f, 0.f);
glVertex3f(-50.f, -50.f, 50.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f( 50.f, 50.f, 50.f);
glVertex3f( 50.f, -50.f, 50.f);
glColor3f(0.f, 1.f, 1.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f(-50.f, -50.f, 50.f);
glColor3f(0.f, 1.f, 1.f);
glVertex3f(50.f, -50.f, -50.f);
glVertex3f(50.f, 50.f, -50.f);
glVertex3f(50.f, 50.f, 50.f);
glVertex3f(50.f, -50.f, 50.f);
glColor3f(1.f, 0.f, 1.f);
glVertex3f(-50.f, -50.f, 50.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f( 50.f, -50.f, -50.f);
glVertex3f( 50.f, -50.f, 50.f);
glColor3f(1.f, 0.f, 1.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, 50.f);
glEnd();
}
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Error code
///
////////////////////////////////////////////////////////////
int main()
{
// Open a connection with the X server
Display* display = XOpenDisplay(NULL);
if (!display)
return EXIT_FAILURE;
// Get the default screen
int screen = DefaultScreen(display);
// Let's create the main window
XSetWindowAttributes attributes;
attributes.background_pixel = BlackPixel(display, screen);
attributes.event_mask = KeyPressMask;
Window window = XCreateWindow(display, RootWindow(display, screen),
0, 0, 650, 330, 0,
DefaultDepth(display, screen),
InputOutput,
DefaultVisual(display, screen),
CWBackPixel | CWEventMask, &attributes);
if (!window)
return EXIT_FAILURE;
// Set the window's name
XStoreName(display, window , "SFML Window");
// Let's create the windows which will serve as containers for our SFML views
Window view1 = XCreateWindow(display, window,
10, 10, 310, 310, 0,
DefaultDepth(display, screen),
InputOutput,
DefaultVisual(display, screen),
0, NULL);
Window view2 = XCreateWindow(display, window,
330, 10, 310, 310, 0,
DefaultDepth(display, screen),
InputOutput,
DefaultVisual(display, screen),
0, NULL);
// Show our windows
XMapWindow(display, window);
XFlush(display);
// Create our SFML views
sf::Window SFMLView1(view1);
sf::Window SFMLView2(view2);
// Create a clock for measuring elapsed time
sf::Clock clock;
// Initialize our views
initialize(SFMLView1);
initialize(SFMLView2);
// Start the event loop
bool running = true;
while (running)
{
while (XPending(display))
{
// Get the next pending event
XEvent event;
XNextEvent(display, &event);
// Process it
switch (event.type)
{
// Any key is pressed: quit
case KeyPress:
running = false;
break;
}
}
// Draw something into our views
draw(SFMLView1, clock.getElapsedTime().asSeconds());
draw(SFMLView2, clock.getElapsedTime().asSeconds() * 0.3f);
// Display the views on screen
SFMLView1.display();
SFMLView2.display();
}
// Close the display
XCloseDisplay(display);
return EXIT_SUCCESS;
}

View file

@ -1,8 +1,8 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/cocoa)
# all source files
set(SRC ${SRCROOT}/CocoaAppDelegate.h
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/cocoa)
# all source files
set(SRC ${SRCROOT}/CocoaAppDelegate.h
${SRCROOT}/CocoaAppDelegate.mm
${SRCROOT}/NSString+stdstring.h
${SRCROOT}/NSString+stdstring.mm
@ -28,9 +28,9 @@ set_target_properties(cocoa PROPERTIES
MACOSX_BUNDLE_INFO_PLIST ${SRCROOT}/resources/Cocoa-Info.plist)
target_link_libraries(cocoa "-framework Cocoa -framework Foundation"
sfml-system sfml-window sfml-graphics)
# set the target's folder (for IDEs that support it, e.g. Visual Studio)
set_target_properties(cocoa PROPERTIES FOLDER "Examples")
# set the target's folder (for IDEs that support it, e.g. Visual Studio)
set_target_properties(cocoa PROPERTIES FOLDER "Examples")
# compile XIB files
find_program(IBTOOL ibtool HINTS "/usr/bin" "${OSX_DEVELOPER_ROOT}/usr/bin")
@ -48,20 +48,20 @@ foreach(XIB ${XIBS})
--compile ${XIB_OUTPUT_PATH}/${XIB}.nib
${XIB_INPUT_PATH}/${XIB}.xib
COMMENT "Compiling ${XIB}.xib")
# deactivated options : --warnings --notices
# deactivated options: --warnings --notices
endforeach()
# add install rule
install(TARGETS cocoa
install(TARGETS cocoa
BUNDLE DESTINATION ${INSTALL_MISC_DIR}/examples/cocoa
COMPONENT examples)
COMPONENT examples)
#
#
# define the cocoa target
# sfml_add_example is not compatible with application bundles !
#
#sfml_add_example(cocoa
# SOURCES ${SRC}
#
#sfml_add_example(cocoa
# SOURCES ${SRC}
# DEPENDS sfml-system sfml-window sfml-graphics)
#

View file

@ -27,11 +27,11 @@
#import <SFML/Graphics.hpp>
/*
* NB : We need pointers for C++ objects fields in Obj-C interface !
* The recommended way is to use PIMP idiom.
* NB: We need pointers for C++ objects fields in Obj-C interface !
* The recommended way is to use PIMPL idiom.
*
* It's elegant. Moreover, we do no constrain
* other file including this one to be Obj-C++.
* It's elegant. Moreover, we do no constrain
* other file including this one to be Obj-C++.
*/
struct SFMLmainWindow;

View file

@ -1,10 +1,10 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/ftp)
# all source files
set(SRC ${SRCROOT}/Ftp.cpp)
# define the ftp target
sfml_add_example(ftp
SOURCES ${SRC}
DEPENDS sfml-network sfml-system)
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/ftp)
# all source files
set(SRC ${SRCROOT}/Ftp.cpp)
# define the ftp target
sfml_add_example(ftp
SOURCES ${SRC}
DEPENDS sfml-network sfml-system)

View file

@ -1,206 +1,206 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network.hpp>
#include <fstream>
#include <iostream>
////////////////////////////////////////////////////////////
/// Print a FTP response into a standard output stream
///
////////////////////////////////////////////////////////////
std::ostream& operator <<(std::ostream& stream, const sf::Ftp::Response& response)
{
return stream << response.getStatus() << response.getMessage();
}
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Choose the server address
sf::IpAddress address;
do
{
std::cout << "Enter the FTP server address : ";
std::cin >> address;
}
while (address == sf::IpAddress::None);
// Connect to the server
sf::Ftp server;
sf::Ftp::Response connectResponse = server.connect(address);
std::cout << connectResponse << std::endl;
if (!connectResponse.isOk())
return EXIT_FAILURE;
// Ask for user name and password
std::string user, password;
std::cout << "User name : ";
std::cin >> user;
std::cout << "Password : ";
std::cin >> password;
// Login to the server
sf::Ftp::Response loginResponse = server.login(user, password);
std::cout << loginResponse << std::endl;
if (!loginResponse.isOk())
return EXIT_FAILURE;
// Main menu
int choice = 0;
do
{
// Main FTP menu
std::cout << std::endl;
std::cout << "Choose an action:" << std::endl;
std::cout << "1. Print working directory" << std::endl;
std::cout << "2. Print contents of working directory" << std::endl;
std::cout << "3. Change directory" << std::endl;
std::cout << "4. Create directory" << std::endl;
std::cout << "5. Delete directory" << std::endl;
std::cout << "6. Rename file" << std::endl;
std::cout << "7. Remove file" << std::endl;
std::cout << "8. Download file" << std::endl;
std::cout << "9. Upload file" << std::endl;
std::cout << "0. Disconnect" << std::endl;
std::cout << std::endl;
std::cout << "Your choice: ";
std::cin >> choice;
std::cout << std::endl;
switch (choice)
{
default :
{
// Wrong choice
std::cout << "Invalid choice!" << std::endl;
std::cin.clear();
std::cin.ignore(10000, '\n');
break;
}
case 1 :
{
// Print the current server directory
sf::Ftp::DirectoryResponse response = server.getWorkingDirectory();
std::cout << response << std::endl;
std::cout << "Current directory is " << response.getDirectory() << std::endl;
break;
}
case 2 :
{
// Print the contents of the current server directory
sf::Ftp::ListingResponse response = server.getDirectoryListing();
std::cout << response << std::endl;
const std::vector<std::string>& names = response.getListing();
for (std::vector<std::string>::const_iterator it = names.begin(); it != names.end(); ++it)
std::cout << *it << std::endl;
break;
}
case 3 :
{
// Change the current directory
std::string directory;
std::cout << "Choose a directory: ";
std::cin >> directory;
std::cout << server.changeDirectory(directory) << std::endl;
break;
}
case 4 :
{
// Create a new directory
std::string directory;
std::cout << "Name of the directory to create: ";
std::cin >> directory;
std::cout << server.createDirectory(directory) << std::endl;
break;
}
case 5 :
{
// Remove an existing directory
std::string directory;
std::cout << "Name of the directory to remove: ";
std::cin >> directory;
std::cout << server.deleteDirectory(directory) << std::endl;
break;
}
case 6 :
{
// Rename a file
std::string source, destination;
std::cout << "Name of the file to rename: ";
std::cin >> source;
std::cout << "New name: ";
std::cin >> destination;
std::cout << server.renameFile(source, destination) << std::endl;
break;
}
case 7 :
{
// Remove an existing directory
std::string filename;
std::cout << "Name of the file to remove: ";
std::cin >> filename;
std::cout << server.deleteFile(filename) << std::endl;
break;
}
case 8 :
{
// Download a file from server
std::string filename, directory;
std::cout << "Filename of the file to download (relative to current directory): ";
std::cin >> filename;
std::cout << "Directory to download the file to: ";
std::cin >> directory;
std::cout << server.download(filename, directory) << std::endl;
break;
}
case 9 :
{
// Upload a file to server
std::string filename, directory;
std::cout << "Path of the file to upload (absolute or relative to working directory): ";
std::cin >> filename;
std::cout << "Directory to upload the file to (relative to current directory): ";
std::cin >> directory;
std::cout << server.upload(filename, directory) << std::endl;
break;
}
case 0 :
{
// Disconnect
break;
}
}
} while (choice != 0);
// Disconnect from the server
std::cout << "Disconnecting from server..." << std::endl;
std::cout << server.disconnect() << std::endl;
// Wait until the user presses 'enter' key
std::cout << "Press enter to exit..." << std::endl;
std::cin.ignore(10000, '\n');
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network.hpp>
#include <fstream>
#include <iostream>
////////////////////////////////////////////////////////////
/// Print a FTP response into a standard output stream
///
////////////////////////////////////////////////////////////
std::ostream& operator <<(std::ostream& stream, const sf::Ftp::Response& response)
{
return stream << response.getStatus() << response.getMessage();
}
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Choose the server address
sf::IpAddress address;
do
{
std::cout << "Enter the FTP server address: ";
std::cin >> address;
}
while (address == sf::IpAddress::None);
// Connect to the server
sf::Ftp server;
sf::Ftp::Response connectResponse = server.connect(address);
std::cout << connectResponse << std::endl;
if (!connectResponse.isOk())
return EXIT_FAILURE;
// Ask for user name and password
std::string user, password;
std::cout << "User name: ";
std::cin >> user;
std::cout << "Password: ";
std::cin >> password;
// Login to the server
sf::Ftp::Response loginResponse = server.login(user, password);
std::cout << loginResponse << std::endl;
if (!loginResponse.isOk())
return EXIT_FAILURE;
// Main menu
int choice = 0;
do
{
// Main FTP menu
std::cout << std::endl;
std::cout << "Choose an action:" << std::endl;
std::cout << "1. Print working directory" << std::endl;
std::cout << "2. Print contents of working directory" << std::endl;
std::cout << "3. Change directory" << std::endl;
std::cout << "4. Create directory" << std::endl;
std::cout << "5. Delete directory" << std::endl;
std::cout << "6. Rename file" << std::endl;
std::cout << "7. Remove file" << std::endl;
std::cout << "8. Download file" << std::endl;
std::cout << "9. Upload file" << std::endl;
std::cout << "0. Disconnect" << std::endl;
std::cout << std::endl;
std::cout << "Your choice: ";
std::cin >> choice;
std::cout << std::endl;
switch (choice)
{
default:
{
// Wrong choice
std::cout << "Invalid choice!" << std::endl;
std::cin.clear();
std::cin.ignore(10000, '\n');
break;
}
case 1:
{
// Print the current server directory
sf::Ftp::DirectoryResponse response = server.getWorkingDirectory();
std::cout << response << std::endl;
std::cout << "Current directory is " << response.getDirectory() << std::endl;
break;
}
case 2:
{
// Print the contents of the current server directory
sf::Ftp::ListingResponse response = server.getDirectoryListing();
std::cout << response << std::endl;
const std::vector<std::string>& names = response.getListing();
for (std::vector<std::string>::const_iterator it = names.begin(); it != names.end(); ++it)
std::cout << *it << std::endl;
break;
}
case 3:
{
// Change the current directory
std::string directory;
std::cout << "Choose a directory: ";
std::cin >> directory;
std::cout << server.changeDirectory(directory) << std::endl;
break;
}
case 4:
{
// Create a new directory
std::string directory;
std::cout << "Name of the directory to create: ";
std::cin >> directory;
std::cout << server.createDirectory(directory) << std::endl;
break;
}
case 5:
{
// Remove an existing directory
std::string directory;
std::cout << "Name of the directory to remove: ";
std::cin >> directory;
std::cout << server.deleteDirectory(directory) << std::endl;
break;
}
case 6:
{
// Rename a file
std::string source, destination;
std::cout << "Name of the file to rename: ";
std::cin >> source;
std::cout << "New name: ";
std::cin >> destination;
std::cout << server.renameFile(source, destination) << std::endl;
break;
}
case 7:
{
// Remove an existing directory
std::string filename;
std::cout << "Name of the file to remove: ";
std::cin >> filename;
std::cout << server.deleteFile(filename) << std::endl;
break;
}
case 8:
{
// Download a file from server
std::string filename, directory;
std::cout << "Filename of the file to download (relative to current directory): ";
std::cin >> filename;
std::cout << "Directory to download the file to: ";
std::cin >> directory;
std::cout << server.download(filename, directory) << std::endl;
break;
}
case 9:
{
// Upload a file to server
std::string filename, directory;
std::cout << "Path of the file to upload (absolute or relative to working directory): ";
std::cin >> filename;
std::cout << "Directory to upload the file to (relative to current directory): ";
std::cin >> directory;
std::cout << server.upload(filename, directory) << std::endl;
break;
}
case 0:
{
// Disconnect
break;
}
}
} while (choice != 0);
// Disconnect from the server
std::cout << "Disconnecting from server..." << std::endl;
std::cout << server.disconnect() << std::endl;
// Wait until the user presses 'enter' key
std::cout << "Press enter to exit..." << std::endl;
std::cin.ignore(10000, '\n');
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}

View file

@ -1,15 +1,15 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/opengl)
# all source files
set(SRC ${SRCROOT}/OpenGL.cpp)
# find OpenGL and GLU
find_package(OpenGL REQUIRED)
include_directories(${OPENGL_INCLUDE_DIR})
set(ADDITIONAL_LIBRARIES ${OPENGL_LIBRARIES})
# define the opengl target
sfml_add_example(opengl GUI_APP
SOURCES ${SRC}
DEPENDS sfml-graphics sfml-window sfml-system ${ADDITIONAL_LIBRARIES})
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/opengl)
# all source files
set(SRC ${SRCROOT}/OpenGL.cpp)
# find OpenGL and GLU
find_package(OpenGL REQUIRED)
include_directories(${OPENGL_INCLUDE_DIR})
set(ADDITIONAL_LIBRARIES ${OPENGL_LIBRARIES})
# define the opengl target
sfml_add_example(opengl GUI_APP
SOURCES ${SRC}
DEPENDS sfml-graphics sfml-window sfml-system ${ADDITIONAL_LIBRARIES})

View file

@ -1,198 +1,198 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Request a 32-bits depth buffer when creating the window
sf::ContextSettings contextSettings;
contextSettings.depthBits = 32;
// Create the main window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML graphics with OpenGL", sf::Style::Default, contextSettings);
window.setVerticalSyncEnabled(true);
// Create a sprite for the background
sf::Texture backgroundTexture;
if (!backgroundTexture.loadFromFile("resources/background.jpg"))
return EXIT_FAILURE;
sf::Sprite background(backgroundTexture);
// Create some text to draw on top of our OpenGL object
sf::Font font;
if (!font.loadFromFile("resources/sansation.ttf"))
return EXIT_FAILURE;
sf::Text text("SFML / OpenGL demo", font);
text.setColor(sf::Color(255, 255, 255, 170));
text.setPosition(250.f, 450.f);
// Make the window the active target for OpenGL calls
// Note: If using sf::Texture or sf::Shader with OpenGL,
// be sure to call sf::Texture::getMaximumSize() and/or
// sf::Shader::isAvailable() at least once before calling
// setActive(), as those functions will cause a context switch
window.setActive();
// Load an OpenGL texture.
// We could directly use a sf::Texture as an OpenGL texture (with its Bind() member function),
// but here we want more control on it (generate mipmaps, ...) so we create a new one from an image
GLuint texture = 0;
{
sf::Image image;
if (!image.loadFromFile("resources/texture.jpg"))
return EXIT_FAILURE;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getSize().x, image.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
}
// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glClearDepth(1.f);
// Disable lighting
glDisable(GL_LIGHTING);
// Configure the viewport (the same size as the window)
glViewport(0, 0, window.getSize().x, window.getSize().y);
// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GLfloat ratio = static_cast<float>(window.getSize().x) / window.getSize().y;
glFrustum(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);
// Bind the texture
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
// Define a 3D cube (6 faces made of 2 triangles composed by 3 vertices)
GLfloat cube[] =
{
// positions // texture coordinates
-20, -20, -20, 0, 0,
-20, 20, -20, 1, 0,
-20, -20, 20, 0, 1,
-20, -20, 20, 0, 1,
-20, 20, -20, 1, 0,
-20, 20, 20, 1, 1,
20, -20, -20, 0, 0,
20, 20, -20, 1, 0,
20, -20, 20, 0, 1,
20, -20, 20, 0, 1,
20, 20, -20, 1, 0,
20, 20, 20, 1, 1,
-20, -20, -20, 0, 0,
20, -20, -20, 1, 0,
-20, -20, 20, 0, 1,
-20, -20, 20, 0, 1,
20, -20, -20, 1, 0,
20, -20, 20, 1, 1,
-20, 20, -20, 0, 0,
20, 20, -20, 1, 0,
-20, 20, 20, 0, 1,
-20, 20, 20, 0, 1,
20, 20, -20, 1, 0,
20, 20, 20, 1, 1,
-20, -20, -20, 0, 0,
20, -20, -20, 1, 0,
-20, 20, -20, 0, 1,
-20, 20, -20, 0, 1,
20, -20, -20, 1, 0,
20, 20, -20, 1, 1,
-20, -20, 20, 0, 0,
20, -20, 20, 1, 0,
-20, 20, 20, 0, 1,
-20, 20, 20, 0, 1,
20, -20, 20, 1, 0,
20, 20, 20, 1, 1
};
// Enable position and texture coordinates vertex components
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 5 * sizeof(GLfloat), cube);
glTexCoordPointer(2, GL_FLOAT, 5 * sizeof(GLfloat), cube + 3);
// Disable normal and color vertex components
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
// Create a clock for measuring the time elapsed
sf::Clock clock;
// Start game loop
while (window.isOpen())
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window : exit
if (event.type == sf::Event::Closed)
window.close();
// Escape key : exit
if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
window.close();
// Adjust the viewport when the window is resized
if (event.type == sf::Event::Resized)
glViewport(0, 0, event.size.width, event.size.height);
}
// Draw the background
window.pushGLStates();
window.draw(background);
window.popGLStates();
// Clear the depth buffer
glClear(GL_DEPTH_BUFFER_BIT);
// We get the position of the mouse cursor, so that we can move the box accordingly
float x = sf::Mouse::getPosition(window).x * 200.f / window.getSize().x - 100.f;
float y = -sf::Mouse::getPosition(window).y * 200.f / window.getSize().y + 100.f;
// Apply some transformations
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(x, y, -100.f);
glRotatef(clock.getElapsedTime().asSeconds() * 50.f, 1.f, 0.f, 0.f);
glRotatef(clock.getElapsedTime().asSeconds() * 30.f, 0.f, 1.f, 0.f);
glRotatef(clock.getElapsedTime().asSeconds() * 90.f, 0.f, 0.f, 1.f);
// Draw the cube
glDrawArrays(GL_TRIANGLES, 0, 36);
// Draw some text on top of our OpenGL object
window.pushGLStates();
window.draw(text);
window.popGLStates();
// Finally, display the rendered frame on screen
window.display();
}
// Don't forget to destroy our texture
glDeleteTextures(1, &texture);
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Request a 32-bits depth buffer when creating the window
sf::ContextSettings contextSettings;
contextSettings.depthBits = 32;
// Create the main window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML graphics with OpenGL", sf::Style::Default, contextSettings);
window.setVerticalSyncEnabled(true);
// Create a sprite for the background
sf::Texture backgroundTexture;
if (!backgroundTexture.loadFromFile("resources/background.jpg"))
return EXIT_FAILURE;
sf::Sprite background(backgroundTexture);
// Create some text to draw on top of our OpenGL object
sf::Font font;
if (!font.loadFromFile("resources/sansation.ttf"))
return EXIT_FAILURE;
sf::Text text("SFML / OpenGL demo", font);
text.setColor(sf::Color(255, 255, 255, 170));
text.setPosition(250.f, 450.f);
// Make the window the active target for OpenGL calls
// Note: If using sf::Texture or sf::Shader with OpenGL,
// be sure to call sf::Texture::getMaximumSize() and/or
// sf::Shader::isAvailable() at least once before calling
// setActive(), as those functions will cause a context switch
window.setActive();
// Load an OpenGL texture.
// We could directly use a sf::Texture as an OpenGL texture (with its Bind() member function),
// but here we want more control on it (generate mipmaps, ...) so we create a new one from an image
GLuint texture = 0;
{
sf::Image image;
if (!image.loadFromFile("resources/texture.jpg"))
return EXIT_FAILURE;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getSize().x, image.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
}
// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glClearDepth(1.f);
// Disable lighting
glDisable(GL_LIGHTING);
// Configure the viewport (the same size as the window)
glViewport(0, 0, window.getSize().x, window.getSize().y);
// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GLfloat ratio = static_cast<float>(window.getSize().x) / window.getSize().y;
glFrustum(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);
// Bind the texture
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
// Define a 3D cube (6 faces made of 2 triangles composed by 3 vertices)
GLfloat cube[] =
{
// positions // texture coordinates
-20, -20, -20, 0, 0,
-20, 20, -20, 1, 0,
-20, -20, 20, 0, 1,
-20, -20, 20, 0, 1,
-20, 20, -20, 1, 0,
-20, 20, 20, 1, 1,
20, -20, -20, 0, 0,
20, 20, -20, 1, 0,
20, -20, 20, 0, 1,
20, -20, 20, 0, 1,
20, 20, -20, 1, 0,
20, 20, 20, 1, 1,
-20, -20, -20, 0, 0,
20, -20, -20, 1, 0,
-20, -20, 20, 0, 1,
-20, -20, 20, 0, 1,
20, -20, -20, 1, 0,
20, -20, 20, 1, 1,
-20, 20, -20, 0, 0,
20, 20, -20, 1, 0,
-20, 20, 20, 0, 1,
-20, 20, 20, 0, 1,
20, 20, -20, 1, 0,
20, 20, 20, 1, 1,
-20, -20, -20, 0, 0,
20, -20, -20, 1, 0,
-20, 20, -20, 0, 1,
-20, 20, -20, 0, 1,
20, -20, -20, 1, 0,
20, 20, -20, 1, 1,
-20, -20, 20, 0, 0,
20, -20, 20, 1, 0,
-20, 20, 20, 0, 1,
-20, 20, 20, 0, 1,
20, -20, 20, 1, 0,
20, 20, 20, 1, 1
};
// Enable position and texture coordinates vertex components
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 5 * sizeof(GLfloat), cube);
glTexCoordPointer(2, GL_FLOAT, 5 * sizeof(GLfloat), cube + 3);
// Disable normal and color vertex components
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
// Create a clock for measuring the time elapsed
sf::Clock clock;
// Start game loop
while (window.isOpen())
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::Closed)
window.close();
// Escape key: exit
if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
window.close();
// Adjust the viewport when the window is resized
if (event.type == sf::Event::Resized)
glViewport(0, 0, event.size.width, event.size.height);
}
// Draw the background
window.pushGLStates();
window.draw(background);
window.popGLStates();
// Clear the depth buffer
glClear(GL_DEPTH_BUFFER_BIT);
// We get the position of the mouse cursor, so that we can move the box accordingly
float x = sf::Mouse::getPosition(window).x * 200.f / window.getSize().x - 100.f;
float y = -sf::Mouse::getPosition(window).y * 200.f / window.getSize().y + 100.f;
// Apply some transformations
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(x, y, -100.f);
glRotatef(clock.getElapsedTime().asSeconds() * 50.f, 1.f, 0.f, 0.f);
glRotatef(clock.getElapsedTime().asSeconds() * 30.f, 0.f, 1.f, 0.f);
glRotatef(clock.getElapsedTime().asSeconds() * 90.f, 0.f, 0.f, 1.f);
// Draw the cube
glDrawArrays(GL_TRIANGLES, 0, 36);
// Draw some text on top of our OpenGL object
window.pushGLStates();
window.draw(text);
window.popGLStates();
// Finally, display the rendered frame on screen
window.display();
}
// Don't forget to destroy our texture
glDeleteTextures(1, &texture);
return EXIT_SUCCESS;
}

View file

@ -1,10 +1,10 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/pong)
# all source files
set(SRC ${SRCROOT}/Pong.cpp)
# define the pong target
sfml_add_example(pong GUI_APP
SOURCES ${SRC}
DEPENDS sfml-audio sfml-graphics sfml-window sfml-system)
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/pong)
# all source files
set(SRC ${SRCROOT}/Pong.cpp)
# define the pong target
sfml_add_example(pong GUI_APP
SOURCES ${SRC}
DEPENDS sfml-audio sfml-graphics sfml-window sfml-system)

View file

@ -1,241 +1,241 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <cmath>
#include <ctime>
#include <cstdlib>
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
std::srand(static_cast<unsigned int>(std::time(NULL)));
// Define some constants
const float pi = 3.14159f;
const int gameWidth = 800;
const int gameHeight = 600;
sf::Vector2f paddleSize(25, 100);
float ballRadius = 10.f;
// Create the window of the application
sf::RenderWindow window(sf::VideoMode(gameWidth, gameHeight, 32), "SFML Pong");
window.setVerticalSyncEnabled(true);
// Load the sounds used in the game
sf::SoundBuffer ballSoundBuffer;
if (!ballSoundBuffer.loadFromFile("resources/ball.wav"))
return EXIT_FAILURE;
sf::Sound ballSound(ballSoundBuffer);
// Create the left paddle
sf::RectangleShape leftPaddle;
leftPaddle.setSize(paddleSize - sf::Vector2f(3, 3));
leftPaddle.setOutlineThickness(3);
leftPaddle.setOutlineColor(sf::Color::Black);
leftPaddle.setFillColor(sf::Color(100, 100, 200));
leftPaddle.setOrigin(paddleSize / 2.f);
// Create the right paddle
sf::RectangleShape rightPaddle;
rightPaddle.setSize(paddleSize - sf::Vector2f(3, 3));
rightPaddle.setOutlineThickness(3);
rightPaddle.setOutlineColor(sf::Color::Black);
rightPaddle.setFillColor(sf::Color(200, 100, 100));
rightPaddle.setOrigin(paddleSize / 2.f);
// Create the ball
sf::CircleShape ball;
ball.setRadius(ballRadius - 3);
ball.setOutlineThickness(3);
ball.setOutlineColor(sf::Color::Black);
ball.setFillColor(sf::Color::White);
ball.setOrigin(ballRadius / 2, ballRadius / 2);
// Load the text font
sf::Font font;
if (!font.loadFromFile("resources/sansation.ttf"))
return EXIT_FAILURE;
// Initialize the pause message
sf::Text pauseMessage;
pauseMessage.setFont(font);
pauseMessage.setCharacterSize(40);
pauseMessage.setPosition(170.f, 150.f);
pauseMessage.setColor(sf::Color::White);
pauseMessage.setString("Welcome to SFML pong!\nPress space to start the game");
// Define the paddles properties
sf::Clock AITimer;
const sf::Time AITime = sf::seconds(0.1f);
const float paddleSpeed = 400.f;
float rightPaddleSpeed = 0.f;
const float ballSpeed = 400.f;
float ballAngle = 0.f; // to be changed later
sf::Clock clock;
bool isPlaying = false;
while (window.isOpen())
{
// Handle events
sf::Event event;
while (window.pollEvent(event))
{
// Window closed or escape key pressed: exit
if ((event.type == sf::Event::Closed) ||
((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)))
{
window.close();
break;
}
// Space key pressed: play
if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Space))
{
if (!isPlaying)
{
// (re)start the game
isPlaying = true;
clock.restart();
// Reset the position of the paddles and ball
leftPaddle.setPosition(10 + paddleSize.x / 2, gameHeight / 2);
rightPaddle.setPosition(gameWidth - 10 - paddleSize.x / 2, gameHeight / 2);
ball.setPosition(gameWidth / 2, gameHeight / 2);
// Reset the ball angle
do
{
// Make sure the ball initial angle is not too much vertical
ballAngle = (std::rand() % 360) * 2 * pi / 360;
}
while (std::abs(std::cos(ballAngle)) < 0.7f);
}
}
}
if (isPlaying)
{
float deltaTime = clock.restart().asSeconds();
// Move the player's paddle
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) &&
(leftPaddle.getPosition().y - paddleSize.y / 2 > 5.f))
{
leftPaddle.move(0.f, -paddleSpeed * deltaTime);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) &&
(leftPaddle.getPosition().y + paddleSize.y / 2 < gameHeight - 5.f))
{
leftPaddle.move(0.f, paddleSpeed * deltaTime);
}
// Move the computer's paddle
if (((rightPaddleSpeed < 0.f) && (rightPaddle.getPosition().y - paddleSize.y / 2 > 5.f)) ||
((rightPaddleSpeed > 0.f) && (rightPaddle.getPosition().y + paddleSize.y / 2 < gameHeight - 5.f)))
{
rightPaddle.move(0.f, rightPaddleSpeed * deltaTime);
}
// Update the computer's paddle direction according to the ball position
if (AITimer.getElapsedTime() > AITime)
{
AITimer.restart();
if (ball.getPosition().y + ballRadius > rightPaddle.getPosition().y + paddleSize.y / 2)
rightPaddleSpeed = paddleSpeed;
else if (ball.getPosition().y - ballRadius < rightPaddle.getPosition().y - paddleSize.y / 2)
rightPaddleSpeed = -paddleSpeed;
else
rightPaddleSpeed = 0.f;
}
// Move the ball
float factor = ballSpeed * deltaTime;
ball.move(std::cos(ballAngle) * factor, std::sin(ballAngle) * factor);
// Check collisions between the ball and the screen
if (ball.getPosition().x - ballRadius < 0.f)
{
isPlaying = false;
pauseMessage.setString("You lost!\nPress space to restart or\nescape to exit");
}
if (ball.getPosition().x + ballRadius > gameWidth)
{
isPlaying = false;
pauseMessage.setString("You won!\nPress space to restart or\nescape to exit");
}
if (ball.getPosition().y - ballRadius < 0.f)
{
ballSound.play();
ballAngle = -ballAngle;
ball.setPosition(ball.getPosition().x, ballRadius + 0.1f);
}
if (ball.getPosition().y + ballRadius > gameHeight)
{
ballSound.play();
ballAngle = -ballAngle;
ball.setPosition(ball.getPosition().x, gameHeight - ballRadius - 0.1f);
}
// Check the collisions between the ball and the paddles
// Left Paddle
if (ball.getPosition().x - ballRadius < leftPaddle.getPosition().x + paddleSize.x / 2 &&
ball.getPosition().x - ballRadius > leftPaddle.getPosition().x &&
ball.getPosition().y + ballRadius >= leftPaddle.getPosition().y - paddleSize.y / 2 &&
ball.getPosition().y - ballRadius <= leftPaddle.getPosition().y + paddleSize.y / 2)
{
if (ball.getPosition().y > leftPaddle.getPosition().y)
ballAngle = pi - ballAngle + (std::rand() % 20) * pi / 180;
else
ballAngle = pi - ballAngle - (std::rand() % 20) * pi / 180;
ballSound.play();
ball.setPosition(leftPaddle.getPosition().x + ballRadius + paddleSize.x / 2 + 0.1f, ball.getPosition().y);
}
// Right Paddle
if (ball.getPosition().x + ballRadius > rightPaddle.getPosition().x - paddleSize.x / 2 &&
ball.getPosition().x + ballRadius < rightPaddle.getPosition().x &&
ball.getPosition().y + ballRadius >= rightPaddle.getPosition().y - paddleSize.y / 2 &&
ball.getPosition().y - ballRadius <= rightPaddle.getPosition().y + paddleSize.y / 2)
{
if (ball.getPosition().y > rightPaddle.getPosition().y)
ballAngle = pi - ballAngle + (std::rand() % 20) * pi / 180;
else
ballAngle = pi - ballAngle - (std::rand() % 20) * pi / 180;
ballSound.play();
ball.setPosition(rightPaddle.getPosition().x - ballRadius - paddleSize.x / 2 - 0.1f, ball.getPosition().y);
}
}
// Clear the window
window.clear(sf::Color(50, 200, 50));
if (isPlaying)
{
// Draw the paddles and the ball
window.draw(leftPaddle);
window.draw(rightPaddle);
window.draw(ball);
}
else
{
// Draw the pause message
window.draw(pauseMessage);
}
// Display things on screen
window.display();
}
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <cmath>
#include <ctime>
#include <cstdlib>
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
std::srand(static_cast<unsigned int>(std::time(NULL)));
// Define some constants
const float pi = 3.14159f;
const int gameWidth = 800;
const int gameHeight = 600;
sf::Vector2f paddleSize(25, 100);
float ballRadius = 10.f;
// Create the window of the application
sf::RenderWindow window(sf::VideoMode(gameWidth, gameHeight, 32), "SFML Pong");
window.setVerticalSyncEnabled(true);
// Load the sounds used in the game
sf::SoundBuffer ballSoundBuffer;
if (!ballSoundBuffer.loadFromFile("resources/ball.wav"))
return EXIT_FAILURE;
sf::Sound ballSound(ballSoundBuffer);
// Create the left paddle
sf::RectangleShape leftPaddle;
leftPaddle.setSize(paddleSize - sf::Vector2f(3, 3));
leftPaddle.setOutlineThickness(3);
leftPaddle.setOutlineColor(sf::Color::Black);
leftPaddle.setFillColor(sf::Color(100, 100, 200));
leftPaddle.setOrigin(paddleSize / 2.f);
// Create the right paddle
sf::RectangleShape rightPaddle;
rightPaddle.setSize(paddleSize - sf::Vector2f(3, 3));
rightPaddle.setOutlineThickness(3);
rightPaddle.setOutlineColor(sf::Color::Black);
rightPaddle.setFillColor(sf::Color(200, 100, 100));
rightPaddle.setOrigin(paddleSize / 2.f);
// Create the ball
sf::CircleShape ball;
ball.setRadius(ballRadius - 3);
ball.setOutlineThickness(3);
ball.setOutlineColor(sf::Color::Black);
ball.setFillColor(sf::Color::White);
ball.setOrigin(ballRadius / 2, ballRadius / 2);
// Load the text font
sf::Font font;
if (!font.loadFromFile("resources/sansation.ttf"))
return EXIT_FAILURE;
// Initialize the pause message
sf::Text pauseMessage;
pauseMessage.setFont(font);
pauseMessage.setCharacterSize(40);
pauseMessage.setPosition(170.f, 150.f);
pauseMessage.setColor(sf::Color::White);
pauseMessage.setString("Welcome to SFML pong!\nPress space to start the game");
// Define the paddles properties
sf::Clock AITimer;
const sf::Time AITime = sf::seconds(0.1f);
const float paddleSpeed = 400.f;
float rightPaddleSpeed = 0.f;
const float ballSpeed = 400.f;
float ballAngle = 0.f; // to be changed later
sf::Clock clock;
bool isPlaying = false;
while (window.isOpen())
{
// Handle events
sf::Event event;
while (window.pollEvent(event))
{
// Window closed or escape key pressed: exit
if ((event.type == sf::Event::Closed) ||
((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)))
{
window.close();
break;
}
// Space key pressed: play
if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Space))
{
if (!isPlaying)
{
// (re)start the game
isPlaying = true;
clock.restart();
// Reset the position of the paddles and ball
leftPaddle.setPosition(10 + paddleSize.x / 2, gameHeight / 2);
rightPaddle.setPosition(gameWidth - 10 - paddleSize.x / 2, gameHeight / 2);
ball.setPosition(gameWidth / 2, gameHeight / 2);
// Reset the ball angle
do
{
// Make sure the ball initial angle is not too much vertical
ballAngle = (std::rand() % 360) * 2 * pi / 360;
}
while (std::abs(std::cos(ballAngle)) < 0.7f);
}
}
}
if (isPlaying)
{
float deltaTime = clock.restart().asSeconds();
// Move the player's paddle
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) &&
(leftPaddle.getPosition().y - paddleSize.y / 2 > 5.f))
{
leftPaddle.move(0.f, -paddleSpeed * deltaTime);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) &&
(leftPaddle.getPosition().y + paddleSize.y / 2 < gameHeight - 5.f))
{
leftPaddle.move(0.f, paddleSpeed * deltaTime);
}
// Move the computer's paddle
if (((rightPaddleSpeed < 0.f) && (rightPaddle.getPosition().y - paddleSize.y / 2 > 5.f)) ||
((rightPaddleSpeed > 0.f) && (rightPaddle.getPosition().y + paddleSize.y / 2 < gameHeight - 5.f)))
{
rightPaddle.move(0.f, rightPaddleSpeed * deltaTime);
}
// Update the computer's paddle direction according to the ball position
if (AITimer.getElapsedTime() > AITime)
{
AITimer.restart();
if (ball.getPosition().y + ballRadius > rightPaddle.getPosition().y + paddleSize.y / 2)
rightPaddleSpeed = paddleSpeed;
else if (ball.getPosition().y - ballRadius < rightPaddle.getPosition().y - paddleSize.y / 2)
rightPaddleSpeed = -paddleSpeed;
else
rightPaddleSpeed = 0.f;
}
// Move the ball
float factor = ballSpeed * deltaTime;
ball.move(std::cos(ballAngle) * factor, std::sin(ballAngle) * factor);
// Check collisions between the ball and the screen
if (ball.getPosition().x - ballRadius < 0.f)
{
isPlaying = false;
pauseMessage.setString("You lost!\nPress space to restart or\nescape to exit");
}
if (ball.getPosition().x + ballRadius > gameWidth)
{
isPlaying = false;
pauseMessage.setString("You won!\nPress space to restart or\nescape to exit");
}
if (ball.getPosition().y - ballRadius < 0.f)
{
ballSound.play();
ballAngle = -ballAngle;
ball.setPosition(ball.getPosition().x, ballRadius + 0.1f);
}
if (ball.getPosition().y + ballRadius > gameHeight)
{
ballSound.play();
ballAngle = -ballAngle;
ball.setPosition(ball.getPosition().x, gameHeight - ballRadius - 0.1f);
}
// Check the collisions between the ball and the paddles
// Left Paddle
if (ball.getPosition().x - ballRadius < leftPaddle.getPosition().x + paddleSize.x / 2 &&
ball.getPosition().x - ballRadius > leftPaddle.getPosition().x &&
ball.getPosition().y + ballRadius >= leftPaddle.getPosition().y - paddleSize.y / 2 &&
ball.getPosition().y - ballRadius <= leftPaddle.getPosition().y + paddleSize.y / 2)
{
if (ball.getPosition().y > leftPaddle.getPosition().y)
ballAngle = pi - ballAngle + (std::rand() % 20) * pi / 180;
else
ballAngle = pi - ballAngle - (std::rand() % 20) * pi / 180;
ballSound.play();
ball.setPosition(leftPaddle.getPosition().x + ballRadius + paddleSize.x / 2 + 0.1f, ball.getPosition().y);
}
// Right Paddle
if (ball.getPosition().x + ballRadius > rightPaddle.getPosition().x - paddleSize.x / 2 &&
ball.getPosition().x + ballRadius < rightPaddle.getPosition().x &&
ball.getPosition().y + ballRadius >= rightPaddle.getPosition().y - paddleSize.y / 2 &&
ball.getPosition().y - ballRadius <= rightPaddle.getPosition().y + paddleSize.y / 2)
{
if (ball.getPosition().y > rightPaddle.getPosition().y)
ballAngle = pi - ballAngle + (std::rand() % 20) * pi / 180;
else
ballAngle = pi - ballAngle - (std::rand() % 20) * pi / 180;
ballSound.play();
ball.setPosition(rightPaddle.getPosition().x - ballRadius - paddleSize.x / 2 - 0.1f, ball.getPosition().y);
}
}
// Clear the window
window.clear(sf::Color(50, 200, 50));
if (isPlaying)
{
// Draw the paddles and the ball
window.draw(leftPaddle);
window.draw(rightPaddle);
window.draw(ball);
}
else
{
// Draw the pause message
window.draw(pauseMessage);
}
// Display things on screen
window.display();
}
return EXIT_SUCCESS;
}

View file

@ -1,12 +1,12 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/shader)
# all source files
set(SRC
${SRCROOT}/Effect.hpp
${SRCROOT}/Shader.cpp)
# define the shader target
sfml_add_example(shader GUI_APP
SOURCES ${SRC}
DEPENDS sfml-graphics sfml-window sfml-system)
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/shader)
# all source files
set(SRC
${SRCROOT}/Effect.hpp
${SRCROOT}/Shader.cpp)
# define the shader target
sfml_add_example(shader GUI_APP
SOURCES ${SRC}
DEPENDS sfml-graphics sfml-window sfml-system)

View file

@ -14,7 +14,7 @@
////////////////////////////////////////////////////////////
class Effect : public sf::Drawable
{
public :
public:
virtual ~Effect()
{
@ -56,7 +56,7 @@ public :
}
}
protected :
protected:
Effect(const std::string& name) :
m_name(name),
@ -70,14 +70,14 @@ protected :
return *s_font;
}
private :
private:
// Virtual functions to be implemented in derived effects
virtual bool onLoad() = 0;
virtual void onUpdate(float time, float x, float y) = 0;
virtual void onDraw(sf::RenderTarget& target, sf::RenderStates states) const = 0;
private :
private:
std::string m_name;
bool m_isLoaded;

View file

@ -1,379 +1,379 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "Effect.hpp"
#include <vector>
#include <cmath>
const sf::Font* Effect::s_font = NULL;
////////////////////////////////////////////////////////////
// "Pixelate" fragment shader
////////////////////////////////////////////////////////////
class Pixelate : public Effect
{
public :
Pixelate() :
Effect("pixelate")
{
}
bool onLoad()
{
// Load the texture and initialize the sprite
if (!m_texture.loadFromFile("resources/background.jpg"))
return false;
m_sprite.setTexture(m_texture);
// Load the shader
if (!m_shader.loadFromFile("resources/pixelate.frag", sf::Shader::Fragment))
return false;
m_shader.setParameter("texture", sf::Shader::CurrentTexture);
return true;
}
void onUpdate(float, float x, float y)
{
m_shader.setParameter("pixel_threshold", (x + y) / 30);
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.shader = &m_shader;
target.draw(m_sprite, states);
}
private:
sf::Texture m_texture;
sf::Sprite m_sprite;
sf::Shader m_shader;
};
////////////////////////////////////////////////////////////
// "Wave" vertex shader + "blur" fragment shader
////////////////////////////////////////////////////////////
class WaveBlur : public Effect
{
public :
WaveBlur() :
Effect("wave + blur")
{
}
bool onLoad()
{
// Create the text
m_text.setString("Praesent suscipit augue in velit pulvinar hendrerit varius purus aliquam.\n"
"Mauris mi odio, bibendum quis fringilla a, laoreet vel orci. Proin vitae vulputate tortor.\n"
"Praesent cursus ultrices justo, ut feugiat ante vehicula quis.\n"
"Donec fringilla scelerisque mauris et viverra.\n"
"Maecenas adipiscing ornare scelerisque. Nullam at libero elit.\n"
"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.\n"
"Nullam leo urna, tincidunt id semper eget, ultricies sed mi.\n"
"Morbi mauris massa, commodo id dignissim vel, lobortis et elit.\n"
"Fusce vel libero sed neque scelerisque venenatis.\n"
"Integer mattis tincidunt quam vitae iaculis.\n"
"Vivamus fringilla sem non velit venenatis fermentum.\n"
"Vivamus varius tincidunt nisi id vehicula.\n"
"Integer ullamcorper, enim vitae euismod rutrum, massa nisl semper ipsum,\n"
"vestibulum sodales sem ante in massa.\n"
"Vestibulum in augue non felis convallis viverra.\n"
"Mauris ultricies dolor sed massa convallis sed aliquet augue fringilla.\n"
"Duis erat eros, porta in accumsan in, blandit quis sem.\n"
"In hac habitasse platea dictumst. Etiam fringilla est id odio dapibus sit amet semper dui laoreet.\n");
m_text.setFont(getFont());
m_text.setCharacterSize(22);
m_text.setPosition(30, 20);
// Load the shader
if (!m_shader.loadFromFile("resources/wave.vert", "resources/blur.frag"))
return false;
return true;
}
void onUpdate(float time, float x, float y)
{
m_shader.setParameter("wave_phase", time);
m_shader.setParameter("wave_amplitude", x * 40, y * 40);
m_shader.setParameter("blur_radius", (x + y) * 0.008f);
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.shader = &m_shader;
target.draw(m_text, states);
}
private:
sf::Text m_text;
sf::Shader m_shader;
};
////////////////////////////////////////////////////////////
// "Storm" vertex shader + "blink" fragment shader
////////////////////////////////////////////////////////////
class StormBlink : public Effect
{
public :
StormBlink() :
Effect("storm + blink")
{
}
bool onLoad()
{
// Create the points
m_points.setPrimitiveType(sf::Points);
for (int i = 0; i < 40000; ++i)
{
float x = static_cast<float>(std::rand() % 800);
float y = static_cast<float>(std::rand() % 600);
sf::Uint8 r = std::rand() % 255;
sf::Uint8 g = std::rand() % 255;
sf::Uint8 b = std::rand() % 255;
m_points.append(sf::Vertex(sf::Vector2f(x, y), sf::Color(r, g, b)));
}
// Load the shader
if (!m_shader.loadFromFile("resources/storm.vert", "resources/blink.frag"))
return false;
return true;
}
void onUpdate(float time, float x, float y)
{
float radius = 200 + std::cos(time) * 150;
m_shader.setParameter("storm_position", x * 800, y * 600);
m_shader.setParameter("storm_inner_radius", radius / 3);
m_shader.setParameter("storm_total_radius", radius);
m_shader.setParameter("blink_alpha", 0.5f + std::cos(time * 3) * 0.25f);
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.shader = &m_shader;
target.draw(m_points, states);
}
private:
sf::VertexArray m_points;
sf::Shader m_shader;
};
////////////////////////////////////////////////////////////
// "Edge" post-effect fragment shader
////////////////////////////////////////////////////////////
class Edge : public Effect
{
public :
Edge() :
Effect("edge post-effect")
{
}
bool onLoad()
{
// Create the off-screen surface
if (!m_surface.create(800, 600))
return false;
m_surface.setSmooth(true);
// Load the textures
if (!m_backgroundTexture.loadFromFile("resources/sfml.png"))
return false;
m_backgroundTexture.setSmooth(true);
if (!m_entityTexture.loadFromFile("resources/devices.png"))
return false;
m_entityTexture.setSmooth(true);
// Initialize the background sprite
m_backgroundSprite.setTexture(m_backgroundTexture);
m_backgroundSprite.setPosition(135, 100);
// Load the moving entities
for (int i = 0; i < 6; ++i)
{
sf::Sprite entity(m_entityTexture, sf::IntRect(96 * i, 0, 96, 96));
m_entities.push_back(entity);
}
// Load the shader
if (!m_shader.loadFromFile("resources/edge.frag", sf::Shader::Fragment))
return false;
m_shader.setParameter("texture", sf::Shader::CurrentTexture);
return true;
}
void onUpdate(float time, float x, float y)
{
m_shader.setParameter("edge_threshold", 1 - (x + y) / 2);
// Update the position of the moving entities
for (std::size_t i = 0; i < m_entities.size(); ++i)
{
sf::Vector2f position;
position.x = std::cos(0.25f * (time * i + (m_entities.size() - i))) * 300 + 350;
position.y = std::sin(0.25f * (time * (m_entities.size() - i) + i)) * 200 + 250;
m_entities[i].setPosition(position);
}
// Render the updated scene to the off-screen surface
m_surface.clear(sf::Color::White);
m_surface.draw(m_backgroundSprite);
for (std::size_t i = 0; i < m_entities.size(); ++i)
m_surface.draw(m_entities[i]);
m_surface.display();
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.shader = &m_shader;
target.draw(sf::Sprite(m_surface.getTexture()), states);
}
private:
sf::RenderTexture m_surface;
sf::Texture m_backgroundTexture;
sf::Texture m_entityTexture;
sf::Sprite m_backgroundSprite;
std::vector<sf::Sprite> m_entities;
sf::Shader m_shader;
};
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Create the main window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Shader");
window.setVerticalSyncEnabled(true);
// Load the application font and pass it to the Effect class
sf::Font font;
if (!font.loadFromFile("resources/sansation.ttf"))
return EXIT_FAILURE;
Effect::setFont(font);
// Create the effects
std::vector<Effect*> effects;
effects.push_back(new Pixelate);
effects.push_back(new WaveBlur);
effects.push_back(new StormBlink);
effects.push_back(new Edge);
std::size_t current = 0;
// Initialize them
for (std::size_t i = 0; i < effects.size(); ++i)
effects[i]->load();
// Create the messages background
sf::Texture textBackgroundTexture;
if (!textBackgroundTexture.loadFromFile("resources/text-background.png"))
return EXIT_FAILURE;
sf::Sprite textBackground(textBackgroundTexture);
textBackground.setPosition(0, 520);
textBackground.setColor(sf::Color(255, 255, 255, 200));
// Create the description text
sf::Text description("Current effect: " + effects[current]->getName(), font, 20);
description.setPosition(10, 530);
description.setColor(sf::Color(80, 80, 80));
// Create the instructions text
sf::Text instructions("Press left and right arrows to change the current shader", font, 20);
instructions.setPosition(280, 555);
instructions.setColor(sf::Color(80, 80, 80));
// Start the game loop
sf::Clock clock;
while (window.isOpen())
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyPressed)
{
switch (event.key.code)
{
// Escape key: exit
case sf::Keyboard::Escape:
window.close();
break;
// Left arrow key: previous shader
case sf::Keyboard::Left:
if (current == 0)
current = effects.size() - 1;
else
current--;
description.setString("Current effect: " + effects[current]->getName());
break;
// Right arrow key: next shader
case sf::Keyboard::Right:
if (current == effects.size() - 1)
current = 0;
else
current++;
description.setString("Current effect: " + effects[current]->getName());
break;
default:
break;
}
}
}
// Update the current example
float x = static_cast<float>(sf::Mouse::getPosition(window).x) / window.getSize().x;
float y = static_cast<float>(sf::Mouse::getPosition(window).y) / window.getSize().y;
effects[current]->update(clock.getElapsedTime().asSeconds(), x, y);
// Clear the window
window.clear(sf::Color(255, 128, 0));
// Draw the current example
window.draw(*effects[current]);
// Draw the text
window.draw(textBackground);
window.draw(instructions);
window.draw(description);
// Finally, display the rendered frame on screen
window.display();
}
// delete the effects
for (std::size_t i = 0; i < effects.size(); ++i)
delete effects[i];
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "Effect.hpp"
#include <vector>
#include <cmath>
const sf::Font* Effect::s_font = NULL;
////////////////////////////////////////////////////////////
// "Pixelate" fragment shader
////////////////////////////////////////////////////////////
class Pixelate : public Effect
{
public:
Pixelate() :
Effect("pixelate")
{
}
bool onLoad()
{
// Load the texture and initialize the sprite
if (!m_texture.loadFromFile("resources/background.jpg"))
return false;
m_sprite.setTexture(m_texture);
// Load the shader
if (!m_shader.loadFromFile("resources/pixelate.frag", sf::Shader::Fragment))
return false;
m_shader.setParameter("texture", sf::Shader::CurrentTexture);
return true;
}
void onUpdate(float, float x, float y)
{
m_shader.setParameter("pixel_threshold", (x + y) / 30);
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.shader = &m_shader;
target.draw(m_sprite, states);
}
private:
sf::Texture m_texture;
sf::Sprite m_sprite;
sf::Shader m_shader;
};
////////////////////////////////////////////////////////////
// "Wave" vertex shader + "blur" fragment shader
////////////////////////////////////////////////////////////
class WaveBlur : public Effect
{
public:
WaveBlur() :
Effect("wave + blur")
{
}
bool onLoad()
{
// Create the text
m_text.setString("Praesent suscipit augue in velit pulvinar hendrerit varius purus aliquam.\n"
"Mauris mi odio, bibendum quis fringilla a, laoreet vel orci. Proin vitae vulputate tortor.\n"
"Praesent cursus ultrices justo, ut feugiat ante vehicula quis.\n"
"Donec fringilla scelerisque mauris et viverra.\n"
"Maecenas adipiscing ornare scelerisque. Nullam at libero elit.\n"
"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.\n"
"Nullam leo urna, tincidunt id semper eget, ultricies sed mi.\n"
"Morbi mauris massa, commodo id dignissim vel, lobortis et elit.\n"
"Fusce vel libero sed neque scelerisque venenatis.\n"
"Integer mattis tincidunt quam vitae iaculis.\n"
"Vivamus fringilla sem non velit venenatis fermentum.\n"
"Vivamus varius tincidunt nisi id vehicula.\n"
"Integer ullamcorper, enim vitae euismod rutrum, massa nisl semper ipsum,\n"
"vestibulum sodales sem ante in massa.\n"
"Vestibulum in augue non felis convallis viverra.\n"
"Mauris ultricies dolor sed massa convallis sed aliquet augue fringilla.\n"
"Duis erat eros, porta in accumsan in, blandit quis sem.\n"
"In hac habitasse platea dictumst. Etiam fringilla est id odio dapibus sit amet semper dui laoreet.\n");
m_text.setFont(getFont());
m_text.setCharacterSize(22);
m_text.setPosition(30, 20);
// Load the shader
if (!m_shader.loadFromFile("resources/wave.vert", "resources/blur.frag"))
return false;
return true;
}
void onUpdate(float time, float x, float y)
{
m_shader.setParameter("wave_phase", time);
m_shader.setParameter("wave_amplitude", x * 40, y * 40);
m_shader.setParameter("blur_radius", (x + y) * 0.008f);
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.shader = &m_shader;
target.draw(m_text, states);
}
private:
sf::Text m_text;
sf::Shader m_shader;
};
////////////////////////////////////////////////////////////
// "Storm" vertex shader + "blink" fragment shader
////////////////////////////////////////////////////////////
class StormBlink : public Effect
{
public:
StormBlink() :
Effect("storm + blink")
{
}
bool onLoad()
{
// Create the points
m_points.setPrimitiveType(sf::Points);
for (int i = 0; i < 40000; ++i)
{
float x = static_cast<float>(std::rand() % 800);
float y = static_cast<float>(std::rand() % 600);
sf::Uint8 r = std::rand() % 255;
sf::Uint8 g = std::rand() % 255;
sf::Uint8 b = std::rand() % 255;
m_points.append(sf::Vertex(sf::Vector2f(x, y), sf::Color(r, g, b)));
}
// Load the shader
if (!m_shader.loadFromFile("resources/storm.vert", "resources/blink.frag"))
return false;
return true;
}
void onUpdate(float time, float x, float y)
{
float radius = 200 + std::cos(time) * 150;
m_shader.setParameter("storm_position", x * 800, y * 600);
m_shader.setParameter("storm_inner_radius", radius / 3);
m_shader.setParameter("storm_total_radius", radius);
m_shader.setParameter("blink_alpha", 0.5f + std::cos(time * 3) * 0.25f);
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.shader = &m_shader;
target.draw(m_points, states);
}
private:
sf::VertexArray m_points;
sf::Shader m_shader;
};
////////////////////////////////////////////////////////////
// "Edge" post-effect fragment shader
////////////////////////////////////////////////////////////
class Edge : public Effect
{
public:
Edge() :
Effect("edge post-effect")
{
}
bool onLoad()
{
// Create the off-screen surface
if (!m_surface.create(800, 600))
return false;
m_surface.setSmooth(true);
// Load the textures
if (!m_backgroundTexture.loadFromFile("resources/sfml.png"))
return false;
m_backgroundTexture.setSmooth(true);
if (!m_entityTexture.loadFromFile("resources/devices.png"))
return false;
m_entityTexture.setSmooth(true);
// Initialize the background sprite
m_backgroundSprite.setTexture(m_backgroundTexture);
m_backgroundSprite.setPosition(135, 100);
// Load the moving entities
for (int i = 0; i < 6; ++i)
{
sf::Sprite entity(m_entityTexture, sf::IntRect(96 * i, 0, 96, 96));
m_entities.push_back(entity);
}
// Load the shader
if (!m_shader.loadFromFile("resources/edge.frag", sf::Shader::Fragment))
return false;
m_shader.setParameter("texture", sf::Shader::CurrentTexture);
return true;
}
void onUpdate(float time, float x, float y)
{
m_shader.setParameter("edge_threshold", 1 - (x + y) / 2);
// Update the position of the moving entities
for (std::size_t i = 0; i < m_entities.size(); ++i)
{
sf::Vector2f position;
position.x = std::cos(0.25f * (time * i + (m_entities.size() - i))) * 300 + 350;
position.y = std::sin(0.25f * (time * (m_entities.size() - i) + i)) * 200 + 250;
m_entities[i].setPosition(position);
}
// Render the updated scene to the off-screen surface
m_surface.clear(sf::Color::White);
m_surface.draw(m_backgroundSprite);
for (std::size_t i = 0; i < m_entities.size(); ++i)
m_surface.draw(m_entities[i]);
m_surface.display();
}
void onDraw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.shader = &m_shader;
target.draw(sf::Sprite(m_surface.getTexture()), states);
}
private:
sf::RenderTexture m_surface;
sf::Texture m_backgroundTexture;
sf::Texture m_entityTexture;
sf::Sprite m_backgroundSprite;
std::vector<sf::Sprite> m_entities;
sf::Shader m_shader;
};
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Create the main window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Shader");
window.setVerticalSyncEnabled(true);
// Load the application font and pass it to the Effect class
sf::Font font;
if (!font.loadFromFile("resources/sansation.ttf"))
return EXIT_FAILURE;
Effect::setFont(font);
// Create the effects
std::vector<Effect*> effects;
effects.push_back(new Pixelate);
effects.push_back(new WaveBlur);
effects.push_back(new StormBlink);
effects.push_back(new Edge);
std::size_t current = 0;
// Initialize them
for (std::size_t i = 0; i < effects.size(); ++i)
effects[i]->load();
// Create the messages background
sf::Texture textBackgroundTexture;
if (!textBackgroundTexture.loadFromFile("resources/text-background.png"))
return EXIT_FAILURE;
sf::Sprite textBackground(textBackgroundTexture);
textBackground.setPosition(0, 520);
textBackground.setColor(sf::Color(255, 255, 255, 200));
// Create the description text
sf::Text description("Current effect: " + effects[current]->getName(), font, 20);
description.setPosition(10, 530);
description.setColor(sf::Color(80, 80, 80));
// Create the instructions text
sf::Text instructions("Press left and right arrows to change the current shader", font, 20);
instructions.setPosition(280, 555);
instructions.setColor(sf::Color(80, 80, 80));
// Start the game loop
sf::Clock clock;
while (window.isOpen())
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyPressed)
{
switch (event.key.code)
{
// Escape key: exit
case sf::Keyboard::Escape:
window.close();
break;
// Left arrow key: previous shader
case sf::Keyboard::Left:
if (current == 0)
current = effects.size() - 1;
else
current--;
description.setString("Current effect: " + effects[current]->getName());
break;
// Right arrow key: next shader
case sf::Keyboard::Right:
if (current == effects.size() - 1)
current = 0;
else
current++;
description.setString("Current effect: " + effects[current]->getName());
break;
default:
break;
}
}
}
// Update the current example
float x = static_cast<float>(sf::Mouse::getPosition(window).x) / window.getSize().x;
float y = static_cast<float>(sf::Mouse::getPosition(window).y) / window.getSize().y;
effects[current]->update(clock.getElapsedTime().asSeconds(), x, y);
// Clear the window
window.clear(sf::Color(255, 128, 0));
// Draw the current example
window.draw(*effects[current]);
// Draw the text
window.draw(textBackground);
window.draw(instructions);
window.draw(description);
// Finally, display the rendered frame on screen
window.display();
}
// delete the effects
for (std::size_t i = 0; i < effects.size(); ++i)
delete effects[i];
return EXIT_SUCCESS;
}

View file

@ -1,20 +1,20 @@
uniform sampler2D texture;
uniform float blur_radius;
void main()
{
vec2 offx = vec2(blur_radius, 0.0);
vec2 offy = vec2(0.0, blur_radius);
vec4 pixel = texture2D(texture, gl_TexCoord[0].xy) * 4.0 +
texture2D(texture, gl_TexCoord[0].xy - offx) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy + offx) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy - offy) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy + offy) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy - offx - offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy - offx + offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx - offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx + offy) * 1.0;
gl_FragColor = gl_Color * (pixel / 16.0);
}
uniform sampler2D texture;
uniform float blur_radius;
void main()
{
vec2 offx = vec2(blur_radius, 0.0);
vec2 offy = vec2(0.0, blur_radius);
vec4 pixel = texture2D(texture, gl_TexCoord[0].xy) * 4.0 +
texture2D(texture, gl_TexCoord[0].xy - offx) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy + offx) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy - offy) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy + offy) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy - offx - offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy - offx + offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx - offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx + offy) * 1.0;
gl_FragColor = gl_Color * (pixel / 16.0);
}

View file

@ -1,32 +1,32 @@
uniform sampler2D texture;
uniform float edge_threshold;
void main()
{
const float offset = 1.0 / 512.0;
vec2 offx = vec2(offset, 0.0);
vec2 offy = vec2(0.0, offset);
vec4 hEdge = texture2D(texture, gl_TexCoord[0].xy - offy) * -2.0 +
texture2D(texture, gl_TexCoord[0].xy + offy) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy - offx - offy) * -1.0 +
texture2D(texture, gl_TexCoord[0].xy - offx + offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx - offy) * -1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx + offy) * 1.0;
vec4 vEdge = texture2D(texture, gl_TexCoord[0].xy - offx) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy + offx) * -2.0 +
texture2D(texture, gl_TexCoord[0].xy - offx - offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy - offx + offy) * -1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx - offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx + offy) * -1.0;
vec3 result = sqrt(hEdge.rgb * hEdge.rgb + vEdge.rgb * vEdge.rgb);
float edge = length(result);
vec4 pixel = gl_Color * texture2D(texture, gl_TexCoord[0].xy);
if (edge > (edge_threshold * 8.0))
pixel.rgb = vec3(0.0, 0.0, 0.0);
else
pixel.a = edge_threshold;
gl_FragColor = pixel;
}
uniform sampler2D texture;
uniform float edge_threshold;
void main()
{
const float offset = 1.0 / 512.0;
vec2 offx = vec2(offset, 0.0);
vec2 offy = vec2(0.0, offset);
vec4 hEdge = texture2D(texture, gl_TexCoord[0].xy - offy) * -2.0 +
texture2D(texture, gl_TexCoord[0].xy + offy) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy - offx - offy) * -1.0 +
texture2D(texture, gl_TexCoord[0].xy - offx + offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx - offy) * -1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx + offy) * 1.0;
vec4 vEdge = texture2D(texture, gl_TexCoord[0].xy - offx) * 2.0 +
texture2D(texture, gl_TexCoord[0].xy + offx) * -2.0 +
texture2D(texture, gl_TexCoord[0].xy - offx - offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy - offx + offy) * -1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx - offy) * 1.0 +
texture2D(texture, gl_TexCoord[0].xy + offx + offy) * -1.0;
vec3 result = sqrt(hEdge.rgb * hEdge.rgb + vEdge.rgb * vEdge.rgb);
float edge = length(result);
vec4 pixel = gl_Color * texture2D(texture, gl_TexCoord[0].xy);
if (edge > (edge_threshold * 8.0))
pixel.rgb = vec3(0.0, 0.0, 0.0);
else
pixel.a = edge_threshold;
gl_FragColor = pixel;
}

View file

@ -1,9 +1,9 @@
uniform sampler2D texture;
uniform float pixel_threshold;
void main()
{
float factor = 1.0 / (pixel_threshold + 0.001);
vec2 pos = floor(gl_TexCoord[0].xy * factor + 0.5) / factor;
gl_FragColor = texture2D(texture, pos) * gl_Color;
}
uniform sampler2D texture;
uniform float pixel_threshold;
void main()
{
float factor = 1.0 / (pixel_threshold + 0.001);
vec2 pos = floor(gl_TexCoord[0].xy * factor + 0.5) / factor;
gl_FragColor = texture2D(texture, pos) * gl_Color;
}

View file

@ -1,12 +1,12 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/sockets)
# all source files
set(SRC ${SRCROOT}/Sockets.cpp
${SRCROOT}/TCP.cpp
${SRCROOT}/UDP.cpp)
# define the sockets target
sfml_add_example(sockets
SOURCES ${SRC}
DEPENDS sfml-network sfml-system)
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/sockets)
# all source files
set(SRC ${SRCROOT}/Sockets.cpp
${SRCROOT}/TCP.cpp
${SRCROOT}/UDP.cpp)
# define the sockets target
sfml_add_example(sockets
SOURCES ${SRC}
DEPENDS sfml-network sfml-system)

View file

@ -1,59 +1,59 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <iostream>
#include <cstdlib>
void runTcpServer(unsigned short port);
void runTcpClient(unsigned short port);
void runUdpServer(unsigned short port);
void runUdpClient(unsigned short port);
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Choose an arbitrary port for opening sockets
const unsigned short port = 50001;
// TCP, UDP or connected UDP ?
char protocol;
std::cout << "Do you want to use TCP (t) or UDP (u) ? ";
std::cin >> protocol;
// Client or server ?
char who;
std::cout << "Do you want to be a server (s) or a client (c) ? ";
std::cin >> who;
if (protocol == 't')
{
// Test the TCP protocol
if (who == 's')
runTcpServer(port);
else
runTcpClient(port);
}
else
{
// Test the unconnected UDP protocol
if (who == 's')
runUdpServer(port);
else
runUdpClient(port);
}
// Wait until the user presses 'enter' key
std::cout << "Press enter to exit..." << std::endl;
std::cin.ignore(10000, '\n');
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <iostream>
#include <cstdlib>
void runTcpServer(unsigned short port);
void runTcpClient(unsigned short port);
void runUdpServer(unsigned short port);
void runUdpClient(unsigned short port);
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Choose an arbitrary port for opening sockets
const unsigned short port = 50001;
// TCP, UDP or connected UDP ?
char protocol;
std::cout << "Do you want to use TCP (t) or UDP (u) ? ";
std::cin >> protocol;
// Client or server ?
char who;
std::cout << "Do you want to be a server (s) or a client (c) ? ";
std::cin >> who;
if (protocol == 't')
{
// Test the TCP protocol
if (who == 's')
runTcpServer(port);
else
runTcpClient(port);
}
else
{
// Test the unconnected UDP protocol
if (who == 's')
runUdpServer(port);
else
runUdpClient(port);
}
// Wait until the user presses 'enter' key
std::cout << "Press enter to exit..." << std::endl;
std::cin.ignore(10000, '\n');
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}

View file

@ -1,81 +1,81 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network.hpp>
#include <iostream>
////////////////////////////////////////////////////////////
/// Launch a server, wait for an incoming connection,
/// send a message and wait for the answer.
///
////////////////////////////////////////////////////////////
void runTcpServer(unsigned short port)
{
// Create a server socket to accept new connections
sf::TcpListener listener;
// Listen to the given port for incoming connections
if (listener.listen(port) != sf::Socket::Done)
return;
std::cout << "Server is listening to port " << port << ", waiting for connections... " << std::endl;
// Wait for a connection
sf::TcpSocket socket;
if (listener.accept(socket) != sf::Socket::Done)
return;
std::cout << "Client connected: " << socket.getRemoteAddress() << std::endl;
// Send a message to the connected client
const char out[] = "Hi, I'm the server";
if (socket.send(out, sizeof(out)) != sf::Socket::Done)
return;
std::cout << "Message sent to the client: \"" << out << "\"" << std::endl;
// Receive a message back from the client
char in[128];
std::size_t received;
if (socket.receive(in, sizeof(in), received) != sf::Socket::Done)
return;
std::cout << "Answer received from the client: \"" << in << "\"" << std::endl;
}
////////////////////////////////////////////////////////////
/// Create a client, connect it to a server, display the
/// welcome message and send an answer.
///
////////////////////////////////////////////////////////////
void runTcpClient(unsigned short port)
{
// Ask for the server address
sf::IpAddress server;
do
{
std::cout << "Type the address or name of the server to connect to: ";
std::cin >> server;
}
while (server == sf::IpAddress::None);
// Create a socket for communicating with the server
sf::TcpSocket socket;
// Connect to the server
if (socket.connect(server, port) != sf::Socket::Done)
return;
std::cout << "Connected to server " << server << std::endl;
// Receive a message from the server
char in[128];
std::size_t received;
if (socket.receive(in, sizeof(in), received) != sf::Socket::Done)
return;
std::cout << "Message received from the server: \"" << in << "\"" << std::endl;
// Send an answer to the server
const char out[] = "Hi, I'm a client";
if (socket.send(out, sizeof(out)) != sf::Socket::Done)
return;
std::cout << "Message sent to the server: \"" << out << "\"" << std::endl;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network.hpp>
#include <iostream>
////////////////////////////////////////////////////////////
/// Launch a server, wait for an incoming connection,
/// send a message and wait for the answer.
///
////////////////////////////////////////////////////////////
void runTcpServer(unsigned short port)
{
// Create a server socket to accept new connections
sf::TcpListener listener;
// Listen to the given port for incoming connections
if (listener.listen(port) != sf::Socket::Done)
return;
std::cout << "Server is listening to port " << port << ", waiting for connections... " << std::endl;
// Wait for a connection
sf::TcpSocket socket;
if (listener.accept(socket) != sf::Socket::Done)
return;
std::cout << "Client connected: " << socket.getRemoteAddress() << std::endl;
// Send a message to the connected client
const char out[] = "Hi, I'm the server";
if (socket.send(out, sizeof(out)) != sf::Socket::Done)
return;
std::cout << "Message sent to the client: \"" << out << "\"" << std::endl;
// Receive a message back from the client
char in[128];
std::size_t received;
if (socket.receive(in, sizeof(in), received) != sf::Socket::Done)
return;
std::cout << "Answer received from the client: \"" << in << "\"" << std::endl;
}
////////////////////////////////////////////////////////////
/// Create a client, connect it to a server, display the
/// welcome message and send an answer.
///
////////////////////////////////////////////////////////////
void runTcpClient(unsigned short port)
{
// Ask for the server address
sf::IpAddress server;
do
{
std::cout << "Type the address or name of the server to connect to: ";
std::cin >> server;
}
while (server == sf::IpAddress::None);
// Create a socket for communicating with the server
sf::TcpSocket socket;
// Connect to the server
if (socket.connect(server, port) != sf::Socket::Done)
return;
std::cout << "Connected to server " << server << std::endl;
// Receive a message from the server
char in[128];
std::size_t received;
if (socket.receive(in, sizeof(in), received) != sf::Socket::Done)
return;
std::cout << "Message received from the server: \"" << in << "\"" << std::endl;
// Send an answer to the server
const char out[] = "Hi, I'm a client";
if (socket.send(out, sizeof(out)) != sf::Socket::Done)
return;
std::cout << "Message sent to the server: \"" << out << "\"" << std::endl;
}

View file

@ -1,72 +1,72 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network.hpp>
#include <iostream>
////////////////////////////////////////////////////////////
/// Launch a server, wait for a message, send an answer.
///
////////////////////////////////////////////////////////////
void runUdpServer(unsigned short port)
{
// Create a socket to receive a message from anyone
sf::UdpSocket socket;
// Listen to messages on the specified port
if (socket.bind(port) != sf::Socket::Done)
return;
std::cout << "Server is listening to port " << port << ", waiting for a message... " << std::endl;
// Wait for a message
char in[128];
std::size_t received;
sf::IpAddress sender;
unsigned short senderPort;
if (socket.receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done)
return;
std::cout << "Message received from client " << sender << ": \"" << in << "\"" << std::endl;
// Send an answer to the client
const char out[] = "Hi, I'm the server";
if (socket.send(out, sizeof(out), sender, senderPort) != sf::Socket::Done)
return;
std::cout << "Message sent to the client: \"" << out << "\"" << std::endl;
}
////////////////////////////////////////////////////////////
/// Send a message to the server, wait for the answer
///
////////////////////////////////////////////////////////////
void runUdpClient(unsigned short port)
{
// Ask for the server address
sf::IpAddress server;
do
{
std::cout << "Type the address or name of the server to connect to: ";
std::cin >> server;
}
while (server == sf::IpAddress::None);
// Create a socket for communicating with the server
sf::UdpSocket socket;
// Send a message to the server
const char out[] = "Hi, I'm a client";
if (socket.send(out, sizeof(out), server, port) != sf::Socket::Done)
return;
std::cout << "Message sent to the server: \"" << out << "\"" << std::endl;
// Receive an answer from anyone (but most likely from the server)
char in[128];
std::size_t received;
sf::IpAddress sender;
unsigned short senderPort;
if (socket.receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done)
return;
std::cout << "Message received from " << sender << ": \"" << in << "\"" << std::endl;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network.hpp>
#include <iostream>
////////////////////////////////////////////////////////////
/// Launch a server, wait for a message, send an answer.
///
////////////////////////////////////////////////////////////
void runUdpServer(unsigned short port)
{
// Create a socket to receive a message from anyone
sf::UdpSocket socket;
// Listen to messages on the specified port
if (socket.bind(port) != sf::Socket::Done)
return;
std::cout << "Server is listening to port " << port << ", waiting for a message... " << std::endl;
// Wait for a message
char in[128];
std::size_t received;
sf::IpAddress sender;
unsigned short senderPort;
if (socket.receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done)
return;
std::cout << "Message received from client " << sender << ": \"" << in << "\"" << std::endl;
// Send an answer to the client
const char out[] = "Hi, I'm the server";
if (socket.send(out, sizeof(out), sender, senderPort) != sf::Socket::Done)
return;
std::cout << "Message sent to the client: \"" << out << "\"" << std::endl;
}
////////////////////////////////////////////////////////////
/// Send a message to the server, wait for the answer
///
////////////////////////////////////////////////////////////
void runUdpClient(unsigned short port)
{
// Ask for the server address
sf::IpAddress server;
do
{
std::cout << "Type the address or name of the server to connect to: ";
std::cin >> server;
}
while (server == sf::IpAddress::None);
// Create a socket for communicating with the server
sf::UdpSocket socket;
// Send a message to the server
const char out[] = "Hi, I'm a client";
if (socket.send(out, sizeof(out), server, port) != sf::Socket::Done)
return;
std::cout << "Message sent to the server: \"" << out << "\"" << std::endl;
// Receive an answer from anyone (but most likely from the server)
char in[128];
std::size_t received;
sf::IpAddress sender;
unsigned short senderPort;
if (socket.receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done)
return;
std::cout << "Message received from " << sender << ": \"" << in << "\"" << std::endl;
}

View file

@ -1,10 +1,10 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/sound)
# all source files
set(SRC ${SRCROOT}/Sound.cpp)
# define the sound target
sfml_add_example(sound
SOURCES ${SRC}
DEPENDS sfml-audio sfml-system)
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/sound)
# all source files
set(SRC ${SRCROOT}/Sound.cpp)
# define the sound target
sfml_add_example(sound
SOURCES ${SRC}
DEPENDS sfml-audio sfml-system)

View file

@ -1,98 +1,98 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio.hpp>
#include <iomanip>
#include <iostream>
////////////////////////////////////////////////////////////
/// Play a sound
///
////////////////////////////////////////////////////////////
void playSound()
{
// Load a sound buffer from a wav file
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("resources/canary.wav"))
return;
// Display sound informations
std::cout << "canary.wav :" << std::endl;
std::cout << " " << buffer.getDuration().asSeconds() << " seconds" << std::endl;
std::cout << " " << buffer.getSampleRate() << " samples / sec" << std::endl;
std::cout << " " << buffer.getChannelCount() << " channels" << std::endl;
// Create a sound instance and play it
sf::Sound sound(buffer);
sound.play();
// Loop while the sound is playing
while (sound.getStatus() == sf::Sound::Playing)
{
// Leave some CPU time for other processes
sf::sleep(sf::milliseconds(100));
// Display the playing position
std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << sound.getPlayingOffset().asSeconds() << " sec ";
std::cout << std::flush;
}
std::cout << std::endl << std::endl;
}
////////////////////////////////////////////////////////////
/// Play a music
///
////////////////////////////////////////////////////////////
void playMusic()
{
// Load an ogg music file
sf::Music music;
if (!music.openFromFile("resources/orchestral.ogg"))
return;
// Display music informations
std::cout << "orchestral.ogg :" << std::endl;
std::cout << " " << music.getDuration().asSeconds() << " seconds" << std::endl;
std::cout << " " << music.getSampleRate() << " samples / sec" << std::endl;
std::cout << " " << music.getChannelCount() << " channels" << std::endl;
// Play it
music.play();
// Loop while the music is playing
while (music.getStatus() == sf::Music::Playing)
{
// Leave some CPU time for other processes
sf::sleep(sf::milliseconds(100));
// Display the playing position
std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << music.getPlayingOffset().asSeconds() << " sec ";
std::cout << std::flush;
}
std::cout << std::endl;
}
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Play a sound
playSound();
// Play a music
playMusic();
// Wait until the user presses 'enter' key
std::cout << "Press enter to exit..." << std::endl;
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio.hpp>
#include <iomanip>
#include <iostream>
////////////////////////////////////////////////////////////
/// Play a sound
///
////////////////////////////////////////////////////////////
void playSound()
{
// Load a sound buffer from a wav file
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("resources/canary.wav"))
return;
// Display sound informations
std::cout << "canary.wav:" << std::endl;
std::cout << " " << buffer.getDuration().asSeconds() << " seconds" << std::endl;
std::cout << " " << buffer.getSampleRate() << " samples / sec" << std::endl;
std::cout << " " << buffer.getChannelCount() << " channels" << std::endl;
// Create a sound instance and play it
sf::Sound sound(buffer);
sound.play();
// Loop while the sound is playing
while (sound.getStatus() == sf::Sound::Playing)
{
// Leave some CPU time for other processes
sf::sleep(sf::milliseconds(100));
// Display the playing position
std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << sound.getPlayingOffset().asSeconds() << " sec ";
std::cout << std::flush;
}
std::cout << std::endl << std::endl;
}
////////////////////////////////////////////////////////////
/// Play a music
///
////////////////////////////////////////////////////////////
void playMusic()
{
// Load an ogg music file
sf::Music music;
if (!music.openFromFile("resources/orchestral.ogg"))
return;
// Display music informations
std::cout << "orchestral.ogg:" << std::endl;
std::cout << " " << music.getDuration().asSeconds() << " seconds" << std::endl;
std::cout << " " << music.getSampleRate() << " samples / sec" << std::endl;
std::cout << " " << music.getChannelCount() << " channels" << std::endl;
// Play it
music.play();
// Loop while the music is playing
while (music.getStatus() == sf::Music::Playing)
{
// Leave some CPU time for other processes
sf::sleep(sf::milliseconds(100));
// Display the playing position
std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << music.getPlayingOffset().asSeconds() << " sec ";
std::cout << std::flush;
}
std::cout << std::endl;
}
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Play a sound
playSound();
// Play a music
playMusic();
// Wait until the user presses 'enter' key
std::cout << "Press enter to exit..." << std::endl;
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}

View file

@ -1,10 +1,10 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/sound_capture)
# all source files
set(SRC ${SRCROOT}/SoundCapture.cpp)
# define the sound-capture target
sfml_add_example(sound-capture
SOURCES ${SRC}
DEPENDS sfml-audio sfml-system)
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/sound_capture)
# all source files
set(SRC ${SRCROOT}/SoundCapture.cpp)
# define the sound-capture target
sfml_add_example(sound-capture
SOURCES ${SRC}
DEPENDS sfml-audio sfml-system)

View file

@ -1,95 +1,95 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio.hpp>
#include <iomanip>
#include <iostream>
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Check that the device can capture audio
if (sf::SoundRecorder::isAvailable() == false)
{
std::cout << "Sorry, audio capture is not supported by your system" << std::endl;
return EXIT_SUCCESS;
}
// Choose the sample rate
unsigned int sampleRate;
std::cout << "Please choose the sample rate for sound capture (44100 is CD quality) : ";
std::cin >> sampleRate;
std::cin.ignore(10000, '\n');
// Wait for user input...
std::cout << "Press enter to start recording audio";
std::cin.ignore(10000, '\n');
// Here we'll use an integrated custom recorder, which saves the captured data into a SoundBuffer
sf::SoundBufferRecorder recorder;
// Audio capture is done in a separate thread, so we can block the main thread while it is capturing
recorder.start(sampleRate);
std::cout << "Recording... press enter to stop";
std::cin.ignore(10000, '\n');
recorder.stop();
// Get the buffer containing the captured data
const sf::SoundBuffer& buffer = recorder.getBuffer();
// Display captured sound informations
std::cout << "Sound information :" << std::endl;
std::cout << " " << buffer.getDuration().asSeconds() << " seconds" << std::endl;
std::cout << " " << buffer.getSampleRate() << " samples / seconds" << std::endl;
std::cout << " " << buffer.getChannelCount() << " channels" << std::endl;
// Choose what to do with the recorded sound data
char choice;
std::cout << "What do you want to do with captured sound (p = play, s = save) ? ";
std::cin >> choice;
std::cin.ignore(10000, '\n');
if (choice == 's')
{
// Choose the filename
std::string filename;
std::cout << "Choose the file to create : ";
std::getline(std::cin, filename);
// Save the buffer
buffer.saveToFile(filename);
}
else
{
// Create a sound instance and play it
sf::Sound sound(buffer);
sound.play();
// Wait until finished
while (sound.getStatus() == sf::Sound::Playing)
{
// Display the playing position
std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << sound.getPlayingOffset().asSeconds() << " sec";
std::cout << std::flush;
// Leave some CPU time for other threads
sf::sleep(sf::milliseconds(100));
}
}
// Finished!
std::cout << std::endl << "Done!" << std::endl;
// Wait until the user presses 'enter' key
std::cout << "Press enter to exit..." << std::endl;
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio.hpp>
#include <iomanip>
#include <iostream>
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Check that the device can capture audio
if (sf::SoundRecorder::isAvailable() == false)
{
std::cout << "Sorry, audio capture is not supported by your system" << std::endl;
return EXIT_SUCCESS;
}
// Choose the sample rate
unsigned int sampleRate;
std::cout << "Please choose the sample rate for sound capture (44100 is CD quality) : ";
std::cin >> sampleRate;
std::cin.ignore(10000, '\n');
// Wait for user input...
std::cout << "Press enter to start recording audio";
std::cin.ignore(10000, '\n');
// Here we'll use an integrated custom recorder, which saves the captured data into a SoundBuffer
sf::SoundBufferRecorder recorder;
// Audio capture is done in a separate thread, so we can block the main thread while it is capturing
recorder.start(sampleRate);
std::cout << "Recording... press enter to stop";
std::cin.ignore(10000, '\n');
recorder.stop();
// Get the buffer containing the captured data
const sf::SoundBuffer& buffer = recorder.getBuffer();
// Display captured sound informations
std::cout << "Sound information:" << std::endl;
std::cout << " " << buffer.getDuration().asSeconds() << " seconds" << std::endl;
std::cout << " " << buffer.getSampleRate() << " samples / seconds" << std::endl;
std::cout << " " << buffer.getChannelCount() << " channels" << std::endl;
// Choose what to do with the recorded sound data
char choice;
std::cout << "What do you want to do with captured sound (p = play, s = save) ? ";
std::cin >> choice;
std::cin.ignore(10000, '\n');
if (choice == 's')
{
// Choose the filename
std::string filename;
std::cout << "Choose the file to create: ";
std::getline(std::cin, filename);
// Save the buffer
buffer.saveToFile(filename);
}
else
{
// Create a sound instance and play it
sf::Sound sound(buffer);
sound.play();
// Wait until finished
while (sound.getStatus() == sf::Sound::Playing)
{
// Display the playing position
std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << sound.getPlayingOffset().asSeconds() << " sec";
std::cout << std::flush;
// Leave some CPU time for other threads
sf::sleep(sf::milliseconds(100));
}
}
// Finished!
std::cout << std::endl << "Done!" << std::endl;
// Wait until the user presses 'enter' key
std::cout << "Press enter to exit..." << std::endl;
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}

View file

@ -1,12 +1,12 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/voip)
# all source files
set(SRC ${SRCROOT}/VoIP.cpp
${SRCROOT}/Client.cpp
${SRCROOT}/Server.cpp)
# define the voip target
sfml_add_example(voip
SOURCES ${SRC}
DEPENDS sfml-audio sfml-network sfml-system)
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/voip)
# all source files
set(SRC ${SRCROOT}/VoIP.cpp
${SRCROOT}/Client.cpp
${SRCROOT}/Server.cpp)
# define the voip target
sfml_add_example(voip
SOURCES ${SRC}
DEPENDS sfml-audio sfml-network sfml-system)

View file

@ -1,129 +1,129 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include <iostream>
const sf::Uint8 audioData = 1;
const sf::Uint8 endOfStream = 2;
////////////////////////////////////////////////////////////
/// Specialization of audio recorder for sending recorded audio
/// data through the network
////////////////////////////////////////////////////////////
class NetworkRecorder : public sf::SoundRecorder
{
public :
////////////////////////////////////////////////////////////
/// Constructor
///
/// \param host Remote host to which send the recording data
/// \param port Port of the remote host
///
////////////////////////////////////////////////////////////
NetworkRecorder(const sf::IpAddress& host, unsigned short port) :
m_host(host),
m_port(port)
{
}
private :
////////////////////////////////////////////////////////////
/// /see SoundRecorder::OnStart
///
////////////////////////////////////////////////////////////
virtual bool onStart()
{
if (m_socket.connect(m_host, m_port) == sf::Socket::Done)
{
std::cout << "Connected to server " << m_host << std::endl;
return true;
}
else
{
return false;
}
}
////////////////////////////////////////////////////////////
/// /see SoundRecorder::ProcessSamples
///
////////////////////////////////////////////////////////////
virtual bool onProcessSamples(const sf::Int16* samples, std::size_t sampleCount)
{
// Pack the audio samples into a network packet
sf::Packet packet;
packet << audioData;
packet.append(samples, sampleCount * sizeof(sf::Int16));
// Send the audio packet to the server
return m_socket.send(packet) == sf::Socket::Done;
}
////////////////////////////////////////////////////////////
/// /see SoundRecorder::OnStop
///
////////////////////////////////////////////////////////////
virtual void onStop()
{
// Send a "end-of-stream" packet
sf::Packet packet;
packet << endOfStream;
m_socket.send(packet);
// Close the socket
m_socket.disconnect();
}
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
sf::IpAddress m_host; ///< Address of the remote host
unsigned short m_port; ///< Remote port
sf::TcpSocket m_socket; ///< Socket used to communicate with the server
};
////////////////////////////////////////////////////////////
/// Create a client, connect it to a running server and
/// start sending him audio data
///
////////////////////////////////////////////////////////////
void doClient(unsigned short port)
{
// Check that the device can capture audio
if (sf::SoundRecorder::isAvailable() == false)
{
std::cout << "Sorry, audio capture is not supported by your system" << std::endl;
return;
}
// Ask for server address
sf::IpAddress server;
do
{
std::cout << "Type address or name of the server to connect to : ";
std::cin >> server;
}
while (server == sf::IpAddress::None);
// Create an instance of our custom recorder
NetworkRecorder recorder(server, port);
// Wait for user input...
std::cin.ignore(10000, '\n');
std::cout << "Press enter to start recording audio";
std::cin.ignore(10000, '\n');
// Start capturing audio data
recorder.start(44100);
std::cout << "Recording... press enter to stop";
std::cin.ignore(10000, '\n');
recorder.stop();
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include <iostream>
const sf::Uint8 audioData = 1;
const sf::Uint8 endOfStream = 2;
////////////////////////////////////////////////////////////
/// Specialization of audio recorder for sending recorded audio
/// data through the network
////////////////////////////////////////////////////////////
class NetworkRecorder : public sf::SoundRecorder
{
public:
////////////////////////////////////////////////////////////
/// Constructor
///
/// \param host Remote host to which send the recording data
/// \param port Port of the remote host
///
////////////////////////////////////////////////////////////
NetworkRecorder(const sf::IpAddress& host, unsigned short port) :
m_host(host),
m_port(port)
{
}
private:
////////////////////////////////////////////////////////////
/// /see SoundRecorder::OnStart
///
////////////////////////////////////////////////////////////
virtual bool onStart()
{
if (m_socket.connect(m_host, m_port) == sf::Socket::Done)
{
std::cout << "Connected to server " << m_host << std::endl;
return true;
}
else
{
return false;
}
}
////////////////////////////////////////////////////////////
/// /see SoundRecorder::ProcessSamples
///
////////////////////////////////////////////////////////////
virtual bool onProcessSamples(const sf::Int16* samples, std::size_t sampleCount)
{
// Pack the audio samples into a network packet
sf::Packet packet;
packet << audioData;
packet.append(samples, sampleCount * sizeof(sf::Int16));
// Send the audio packet to the server
return m_socket.send(packet) == sf::Socket::Done;
}
////////////////////////////////////////////////////////////
/// /see SoundRecorder::OnStop
///
////////////////////////////////////////////////////////////
virtual void onStop()
{
// Send a "end-of-stream" packet
sf::Packet packet;
packet << endOfStream;
m_socket.send(packet);
// Close the socket
m_socket.disconnect();
}
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
sf::IpAddress m_host; ///< Address of the remote host
unsigned short m_port; ///< Remote port
sf::TcpSocket m_socket; ///< Socket used to communicate with the server
};
////////////////////////////////////////////////////////////
/// Create a client, connect it to a running server and
/// start sending him audio data
///
////////////////////////////////////////////////////////////
void doClient(unsigned short port)
{
// Check that the device can capture audio
if (sf::SoundRecorder::isAvailable() == false)
{
std::cout << "Sorry, audio capture is not supported by your system" << std::endl;
return;
}
// Ask for server address
sf::IpAddress server;
do
{
std::cout << "Type address or name of the server to connect to: ";
std::cin >> server;
}
while (server == sf::IpAddress::None);
// Create an instance of our custom recorder
NetworkRecorder recorder(server, port);
// Wait for user input...
std::cin.ignore(10000, '\n');
std::cout << "Press enter to start recording audio";
std::cin.ignore(10000, '\n');
// Start capturing audio data
recorder.start(44100);
std::cout << "Recording... press enter to stop";
std::cin.ignore(10000, '\n');
recorder.stop();
}

View file

@ -1,200 +1,200 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include <iomanip>
#include <iostream>
#include <iterator>
const sf::Uint8 audioData = 1;
const sf::Uint8 endOfStream = 2;
////////////////////////////////////////////////////////////
/// Customized sound stream for acquiring audio data
/// from the network
////////////////////////////////////////////////////////////
class NetworkAudioStream : public sf::SoundStream
{
public :
////////////////////////////////////////////////////////////
/// Default constructor
///
////////////////////////////////////////////////////////////
NetworkAudioStream() :
m_offset (0),
m_hasFinished(false)
{
// Set the sound parameters
initialize(1, 44100);
}
////////////////////////////////////////////////////////////
/// Run the server, stream audio data from the client
///
////////////////////////////////////////////////////////////
void start(unsigned short port)
{
if (!m_hasFinished)
{
// Listen to the given port for incoming connections
if (m_listener.listen(port) != sf::Socket::Done)
return;
std::cout << "Server is listening to port " << port << ", waiting for connections... " << std::endl;
// Wait for a connection
if (m_listener.accept(m_client) != sf::Socket::Done)
return;
std::cout << "Client connected: " << m_client.getRemoteAddress() << std::endl;
// Start playback
play();
// Start receiving audio data
receiveLoop();
}
else
{
// Start playback
play();
}
}
private :
////////////////////////////////////////////////////////////
/// /see SoundStream::OnGetData
///
////////////////////////////////////////////////////////////
virtual bool onGetData(sf::SoundStream::Chunk& data)
{
// We have reached the end of the buffer and all audio data have been played : we can stop playback
if ((m_offset >= m_samples.size()) && m_hasFinished)
return false;
// No new data has arrived since last update : wait until we get some
while ((m_offset >= m_samples.size()) && !m_hasFinished)
sf::sleep(sf::milliseconds(10));
// Copy samples into a local buffer to avoid synchronization problems
// (don't forget that we run in two separate threads)
{
sf::Lock lock(m_mutex);
m_tempBuffer.assign(m_samples.begin() + m_offset, m_samples.end());
}
// Fill audio data to pass to the stream
data.samples = &m_tempBuffer[0];
data.sampleCount = m_tempBuffer.size();
// Update the playing offset
m_offset += m_tempBuffer.size();
return true;
}
////////////////////////////////////////////////////////////
/// /see SoundStream::OnSeek
///
////////////////////////////////////////////////////////////
virtual void onSeek(sf::Time timeOffset)
{
m_offset = timeOffset.asMilliseconds() * getSampleRate() * getChannelCount() / 1000;
}
////////////////////////////////////////////////////////////
/// Get audio data from the client until playback is stopped
///
////////////////////////////////////////////////////////////
void receiveLoop()
{
while (!m_hasFinished)
{
// Get waiting audio data from the network
sf::Packet packet;
if (m_client.receive(packet) != sf::Socket::Done)
break;
// Extract the message ID
sf::Uint8 id;
packet >> id;
if (id == audioData)
{
// Extract audio samples from the packet, and append it to our samples buffer
const sf::Int16* samples = reinterpret_cast<const sf::Int16*>(static_cast<const char*>(packet.getData()) + 1);
std::size_t sampleCount = (packet.getDataSize() - 1) / sizeof(sf::Int16);
// Don't forget that the other thread can access the sample array at any time
// (so we protect any operation on it with the mutex)
{
sf::Lock lock(m_mutex);
std::copy(samples, samples + sampleCount, std::back_inserter(m_samples));
}
}
else if (id == endOfStream)
{
// End of stream reached : we stop receiving audio data
std::cout << "Audio data has been 100% received!" << std::endl;
m_hasFinished = true;
}
else
{
// Something's wrong...
std::cout << "Invalid packet received..." << std::endl;
m_hasFinished = true;
}
}
}
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
sf::TcpListener m_listener;
sf::TcpSocket m_client;
sf::Mutex m_mutex;
std::vector<sf::Int16> m_samples;
std::vector<sf::Int16> m_tempBuffer;
std::size_t m_offset;
bool m_hasFinished;
};
////////////////////////////////////////////////////////////
/// Launch a server and wait for incoming audio data from
/// a connected client
///
////////////////////////////////////////////////////////////
void doServer(unsigned short port)
{
// Build an audio stream to play sound data as it is received through the network
NetworkAudioStream audioStream;
audioStream.start(port);
// Loop until the sound playback is finished
while (audioStream.getStatus() != sf::SoundStream::Stopped)
{
// Leave some CPU time for other threads
sf::sleep(sf::milliseconds(100));
}
std::cin.ignore(10000, '\n');
// Wait until the user presses 'enter' key
std::cout << "Press enter to replay the sound..." << std::endl;
std::cin.ignore(10000, '\n');
// Replay the sound (just to make sure replaying the received data is OK)
audioStream.play();
// Loop until the sound playback is finished
while (audioStream.getStatus() != sf::SoundStream::Stopped)
{
// Leave some CPU time for other threads
sf::sleep(sf::milliseconds(100));
}
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include <iomanip>
#include <iostream>
#include <iterator>
const sf::Uint8 audioData = 1;
const sf::Uint8 endOfStream = 2;
////////////////////////////////////////////////////////////
/// Customized sound stream for acquiring audio data
/// from the network
////////////////////////////////////////////////////////////
class NetworkAudioStream : public sf::SoundStream
{
public:
////////////////////////////////////////////////////////////
/// Default constructor
///
////////////////////////////////////////////////////////////
NetworkAudioStream() :
m_offset (0),
m_hasFinished(false)
{
// Set the sound parameters
initialize(1, 44100);
}
////////////////////////////////////////////////////////////
/// Run the server, stream audio data from the client
///
////////////////////////////////////////////////////////////
void start(unsigned short port)
{
if (!m_hasFinished)
{
// Listen to the given port for incoming connections
if (m_listener.listen(port) != sf::Socket::Done)
return;
std::cout << "Server is listening to port " << port << ", waiting for connections... " << std::endl;
// Wait for a connection
if (m_listener.accept(m_client) != sf::Socket::Done)
return;
std::cout << "Client connected: " << m_client.getRemoteAddress() << std::endl;
// Start playback
play();
// Start receiving audio data
receiveLoop();
}
else
{
// Start playback
play();
}
}
private:
////////////////////////////////////////////////////////////
/// /see SoundStream::OnGetData
///
////////////////////////////////////////////////////////////
virtual bool onGetData(sf::SoundStream::Chunk& data)
{
// We have reached the end of the buffer and all audio data have been played: we can stop playback
if ((m_offset >= m_samples.size()) && m_hasFinished)
return false;
// No new data has arrived since last update: wait until we get some
while ((m_offset >= m_samples.size()) && !m_hasFinished)
sf::sleep(sf::milliseconds(10));
// Copy samples into a local buffer to avoid synchronization problems
// (don't forget that we run in two separate threads)
{
sf::Lock lock(m_mutex);
m_tempBuffer.assign(m_samples.begin() + m_offset, m_samples.end());
}
// Fill audio data to pass to the stream
data.samples = &m_tempBuffer[0];
data.sampleCount = m_tempBuffer.size();
// Update the playing offset
m_offset += m_tempBuffer.size();
return true;
}
////////////////////////////////////////////////////////////
/// /see SoundStream::OnSeek
///
////////////////////////////////////////////////////////////
virtual void onSeek(sf::Time timeOffset)
{
m_offset = timeOffset.asMilliseconds() * getSampleRate() * getChannelCount() / 1000;
}
////////////////////////////////////////////////////////////
/// Get audio data from the client until playback is stopped
///
////////////////////////////////////////////////////////////
void receiveLoop()
{
while (!m_hasFinished)
{
// Get waiting audio data from the network
sf::Packet packet;
if (m_client.receive(packet) != sf::Socket::Done)
break;
// Extract the message ID
sf::Uint8 id;
packet >> id;
if (id == audioData)
{
// Extract audio samples from the packet, and append it to our samples buffer
const sf::Int16* samples = reinterpret_cast<const sf::Int16*>(static_cast<const char*>(packet.getData()) + 1);
std::size_t sampleCount = (packet.getDataSize() - 1) / sizeof(sf::Int16);
// Don't forget that the other thread can access the sample array at any time
// (so we protect any operation on it with the mutex)
{
sf::Lock lock(m_mutex);
std::copy(samples, samples + sampleCount, std::back_inserter(m_samples));
}
}
else if (id == endOfStream)
{
// End of stream reached: we stop receiving audio data
std::cout << "Audio data has been 100% received!" << std::endl;
m_hasFinished = true;
}
else
{
// Something's wrong...
std::cout << "Invalid packet received..." << std::endl;
m_hasFinished = true;
}
}
}
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
sf::TcpListener m_listener;
sf::TcpSocket m_client;
sf::Mutex m_mutex;
std::vector<sf::Int16> m_samples;
std::vector<sf::Int16> m_tempBuffer;
std::size_t m_offset;
bool m_hasFinished;
};
////////////////////////////////////////////////////////////
/// Launch a server and wait for incoming audio data from
/// a connected client
///
////////////////////////////////////////////////////////////
void doServer(unsigned short port)
{
// Build an audio stream to play sound data as it is received through the network
NetworkAudioStream audioStream;
audioStream.start(port);
// Loop until the sound playback is finished
while (audioStream.getStatus() != sf::SoundStream::Stopped)
{
// Leave some CPU time for other threads
sf::sleep(sf::milliseconds(100));
}
std::cin.ignore(10000, '\n');
// Wait until the user presses 'enter' key
std::cout << "Press enter to replay the sound..." << std::endl;
std::cin.ignore(10000, '\n');
// Replay the sound (just to make sure replaying the received data is OK)
audioStream.play();
// Loop until the sound playback is finished
while (audioStream.getStatus() != sf::SoundStream::Stopped)
{
// Leave some CPU time for other threads
sf::sleep(sf::milliseconds(100));
}
}

View file

@ -1,50 +1,50 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <iomanip>
#include <iostream>
#include <cstdlib>
////////////////////////////////////////////////////////////
// Function prototypes
// (I'm too lazy to put them into separate headers...)
////////////////////////////////////////////////////////////
void doClient(unsigned short port);
void doServer(unsigned short port);
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Choose a random port for opening sockets (ports < 1024 are reserved)
const unsigned short port = 2435;
// Client or server ?
char who;
std::cout << "Do you want to be a server ('s') or a client ('c') ? ";
std::cin >> who;
if (who == 's')
{
// Run as a server
doServer(port);
}
else
{
// Run as a client
doClient(port);
}
// Wait until the user presses 'enter' key
std::cout << "Press enter to exit..." << std::endl;
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <iomanip>
#include <iostream>
#include <cstdlib>
////////////////////////////////////////////////////////////
// Function prototypes
// (I'm too lazy to put them into separate headers...)
////////////////////////////////////////////////////////////
void doClient(unsigned short port);
void doServer(unsigned short port);
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Choose a random port for opening sockets (ports < 1024 are reserved)
const unsigned short port = 2435;
// Client or server ?
char who;
std::cout << "Do you want to be a server ('s') or a client ('c') ? ";
std::cin >> who;
if (who == 's')
{
// Run as a server
doServer(port);
}
else
{
// Run as a client
doClient(port);
}
// Wait until the user presses 'enter' key
std::cout << "Press enter to exit..." << std::endl;
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}

View file

@ -1,10 +1,10 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/win32)
# all source files
set(SRC ${SRCROOT}/Win32.cpp)
# define the win32 target
sfml_add_example(win32 GUI_APP
SOURCES ${SRC}
DEPENDS sfml-graphics sfml-window sfml-system)
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/win32)
# all source files
set(SRC ${SRCROOT}/Win32.cpp)
# define the win32 target
sfml_add_example(win32 GUI_APP
SOURCES ${SRC}
DEPENDS sfml-graphics sfml-window sfml-system)

View file

@ -1,130 +1,130 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <windows.h>
#include <cmath>
HWND button;
////////////////////////////////////////////////////////////
/// Function called whenever one of our windows receives a message
///
////////////////////////////////////////////////////////////
LRESULT CALLBACK onEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
// Quit when we close the main window
case WM_CLOSE :
{
PostQuitMessage(0);
return 0;
}
// Quit when we click the "quit" button
case WM_COMMAND :
{
if (reinterpret_cast<HWND>(lParam) == button)
{
PostQuitMessage(0);
return 0;
}
}
}
return DefWindowProc(handle, message, wParam, lParam);
}
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \param Instance : Instance of the application
///
/// \return Error code
///
////////////////////////////////////////////////////////////
INT WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, INT)
{
// Define a class for our main window
WNDCLASS windowClass;
windowClass.style = 0;
windowClass.lpfnWndProc = &onEvent;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = instance;
windowClass.hIcon = NULL;
windowClass.hCursor = 0;
windowClass.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND);
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = TEXT("SFML App");
RegisterClass(&windowClass);
// Let's create the main window
HWND window = CreateWindow(TEXT("SFML App"), TEXT("SFML Win32"), WS_SYSMENU | WS_VISIBLE, 200, 200, 660, 520, NULL, NULL, instance, NULL);
// Add a button for exiting
button = CreateWindow(TEXT("BUTTON"), TEXT("Quit"), WS_CHILD | WS_VISIBLE, 560, 440, 80, 40, window, NULL, instance, NULL);
// Let's create two SFML views
HWND view1 = CreateWindow(TEXT("STATIC"), NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 20, 20, 300, 400, window, NULL, instance, NULL);
HWND view2 = CreateWindow(TEXT("STATIC"), NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 340, 20, 300, 400, window, NULL, instance, NULL);
sf::RenderWindow SFMLView1(view1);
sf::RenderWindow SFMLView2(view2);
// Load some textures to display
sf::Texture texture1, texture2;
if (!texture1.loadFromFile("resources/image1.jpg") || !texture2.loadFromFile("resources/image2.jpg"))
return EXIT_FAILURE;
sf::Sprite sprite1(texture1);
sf::Sprite sprite2(texture2);
sprite1.setOrigin(sf::Vector2f(texture1.getSize()) / 2.f);
sprite1.setPosition(sprite1.getOrigin());
// Create a clock for measuring elapsed time
sf::Clock clock;
// Loop until a WM_QUIT message is received
MSG message;
message.message = static_cast<UINT>(~WM_QUIT);
while (message.message != WM_QUIT)
{
if (PeekMessage(&message, NULL, 0, 0, PM_REMOVE))
{
// If a message was waiting in the message queue, process it
TranslateMessage(&message);
DispatchMessage(&message);
}
else
{
float time = clock.getElapsedTime().asSeconds();
// Clear views
SFMLView1.clear();
SFMLView2.clear();
// Draw sprite 1 on view 1
sprite1.setRotation(time * 100);
SFMLView1.draw(sprite1);
// Draw sprite 2 on view 2
sprite2.setPosition(std::cos(time) * 100.f, 0.f);
SFMLView2.draw(sprite2);
// Display each view on screen
SFMLView1.display();
SFMLView2.display();
}
}
// Destroy the main window (all its child controls will be destroyed)
DestroyWindow(window);
// Don't forget to unregister the window class
UnregisterClass(TEXT("SFML App"), instance);
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <windows.h>
#include <cmath>
HWND button;
////////////////////////////////////////////////////////////
/// Function called whenever one of our windows receives a message
///
////////////////////////////////////////////////////////////
LRESULT CALLBACK onEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
// Quit when we close the main window
case WM_CLOSE:
{
PostQuitMessage(0);
return 0;
}
// Quit when we click the "quit" button
case WM_COMMAND:
{
if (reinterpret_cast<HWND>(lParam) == button)
{
PostQuitMessage(0);
return 0;
}
}
}
return DefWindowProc(handle, message, wParam, lParam);
}
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \param Instance: Instance of the application
///
/// \return Error code
///
////////////////////////////////////////////////////////////
INT WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, INT)
{
// Define a class for our main window
WNDCLASS windowClass;
windowClass.style = 0;
windowClass.lpfnWndProc = &onEvent;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = instance;
windowClass.hIcon = NULL;
windowClass.hCursor = 0;
windowClass.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND);
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = TEXT("SFML App");
RegisterClass(&windowClass);
// Let's create the main window
HWND window = CreateWindow(TEXT("SFML App"), TEXT("SFML Win32"), WS_SYSMENU | WS_VISIBLE, 200, 200, 660, 520, NULL, NULL, instance, NULL);
// Add a button for exiting
button = CreateWindow(TEXT("BUTTON"), TEXT("Quit"), WS_CHILD | WS_VISIBLE, 560, 440, 80, 40, window, NULL, instance, NULL);
// Let's create two SFML views
HWND view1 = CreateWindow(TEXT("STATIC"), NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 20, 20, 300, 400, window, NULL, instance, NULL);
HWND view2 = CreateWindow(TEXT("STATIC"), NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 340, 20, 300, 400, window, NULL, instance, NULL);
sf::RenderWindow SFMLView1(view1);
sf::RenderWindow SFMLView2(view2);
// Load some textures to display
sf::Texture texture1, texture2;
if (!texture1.loadFromFile("resources/image1.jpg") || !texture2.loadFromFile("resources/image2.jpg"))
return EXIT_FAILURE;
sf::Sprite sprite1(texture1);
sf::Sprite sprite2(texture2);
sprite1.setOrigin(sf::Vector2f(texture1.getSize()) / 2.f);
sprite1.setPosition(sprite1.getOrigin());
// Create a clock for measuring elapsed time
sf::Clock clock;
// Loop until a WM_QUIT message is received
MSG message;
message.message = static_cast<UINT>(~WM_QUIT);
while (message.message != WM_QUIT)
{
if (PeekMessage(&message, NULL, 0, 0, PM_REMOVE))
{
// If a message was waiting in the message queue, process it
TranslateMessage(&message);
DispatchMessage(&message);
}
else
{
float time = clock.getElapsedTime().asSeconds();
// Clear views
SFMLView1.clear();
SFMLView2.clear();
// Draw sprite 1 on view 1
sprite1.setRotation(time * 100);
SFMLView1.draw(sprite1);
// Draw sprite 2 on view 2
sprite2.setPosition(std::cos(time) * 100.f, 0.f);
SFMLView2.draw(sprite2);
// Display each view on screen
SFMLView1.display();
SFMLView2.display();
}
}
// Destroy the main window (all its child controls will be destroyed)
DestroyWindow(window);
// Don't forget to unregister the window class
UnregisterClass(TEXT("SFML App"), instance);
return EXIT_SUCCESS;
}

View file

@ -1,15 +1,15 @@
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/window)
# all source files
set(SRC ${SRCROOT}/Window.cpp)
# find OpenGL and GLU
find_package(OpenGL REQUIRED)
include_directories(${OPENGL_INCLUDE_DIR})
set(ADDITIONAL_LIBRARIES ${OPENGL_LIBRARIES})
# define the window target
sfml_add_example(window GUI_APP
SOURCES ${SRC}
DEPENDS sfml-window sfml-system ${ADDITIONAL_LIBRARIES})
set(SRCROOT ${PROJECT_SOURCE_DIR}/examples/window)
# all source files
set(SRC ${SRCROOT}/Window.cpp)
# find OpenGL and GLU
find_package(OpenGL REQUIRED)
include_directories(${OPENGL_INCLUDE_DIR})
set(ADDITIONAL_LIBRARIES ${OPENGL_LIBRARIES})
# define the window target
sfml_add_example(window GUI_APP
SOURCES ${SRC}
DEPENDS sfml-window sfml-system ${ADDITIONAL_LIBRARIES})

View file

@ -1,146 +1,146 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window.hpp>
#include <SFML/OpenGL.hpp>
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Request a 32-bits depth buffer when creating the window
sf::ContextSettings contextSettings;
contextSettings.depthBits = 32;
// Create the main window
sf::Window window(sf::VideoMode(640, 480), "SFML window with OpenGL", sf::Style::Default, contextSettings);
// Make it the active window for OpenGL calls
window.setActive();
// Set the color and depth clear values
glClearDepth(1.f);
glClearColor(0.f, 0.f, 0.f, 1.f);
// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
// Disable lighting and texturing
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
// Configure the viewport (the same size as the window)
glViewport(0, 0, window.getSize().x, window.getSize().y);
// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GLfloat ratio = static_cast<float>(window.getSize().x) / window.getSize().y;
glFrustum(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);
// Define a 3D cube (6 faces made of 2 triangles composed by 3 vertices)
GLfloat cube[] =
{
// positions // colors (r, g, b, a)
-50, -50, -50, 0, 0, 1, 1,
-50, 50, -50, 0, 0, 1, 1,
-50, -50, 50, 0, 0, 1, 1,
-50, -50, 50, 0, 0, 1, 1,
-50, 50, -50, 0, 0, 1, 1,
-50, 50, 50, 0, 0, 1, 1,
50, -50, -50, 0, 1, 0, 1,
50, 50, -50, 0, 1, 0, 1,
50, -50, 50, 0, 1, 0, 1,
50, -50, 50, 0, 1, 0, 1,
50, 50, -50, 0, 1, 0, 1,
50, 50, 50, 0, 1, 0, 1,
-50, -50, -50, 1, 0, 0, 1,
50, -50, -50, 1, 0, 0, 1,
-50, -50, 50, 1, 0, 0, 1,
-50, -50, 50, 1, 0, 0, 1,
50, -50, -50, 1, 0, 0, 1,
50, -50, 50, 1, 0, 0, 1,
-50, 50, -50, 0, 1, 1, 1,
50, 50, -50, 0, 1, 1, 1,
-50, 50, 50, 0, 1, 1, 1,
-50, 50, 50, 0, 1, 1, 1,
50, 50, -50, 0, 1, 1, 1,
50, 50, 50, 0, 1, 1, 1,
-50, -50, -50, 1, 0, 1, 1,
50, -50, -50, 1, 0, 1, 1,
-50, 50, -50, 1, 0, 1, 1,
-50, 50, -50, 1, 0, 1, 1,
50, -50, -50, 1, 0, 1, 1,
50, 50, -50, 1, 0, 1, 1,
-50, -50, 50, 1, 1, 0, 1,
50, -50, 50, 1, 1, 0, 1,
-50, 50, 50, 1, 1, 0, 1,
-50, 50, 50, 1, 1, 0, 1,
50, -50, 50, 1, 1, 0, 1,
50, 50, 50, 1, 1, 0, 1,
};
// Enable position and color vertex components
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 7 * sizeof(GLfloat), cube);
glColorPointer(4, GL_FLOAT, 7 * sizeof(GLfloat), cube + 3);
// Disable normal and texture coordinates vertex components
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// Create a clock for measuring the time elapsed
sf::Clock clock;
// Start the game loop
while (window.isOpen())
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::Closed)
window.close();
// Escape key: exit
if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
window.close();
// Resize event: adjust the viewport
if (event.type == sf::Event::Resized)
glViewport(0, 0, event.size.width, event.size.height);
}
// Clear the color and depth buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Apply some transformations to rotate the cube
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.f, 0.f, -200.f);
glRotatef(clock.getElapsedTime().asSeconds() * 50, 1.f, 0.f, 0.f);
glRotatef(clock.getElapsedTime().asSeconds() * 30, 0.f, 1.f, 0.f);
glRotatef(clock.getElapsedTime().asSeconds() * 90, 0.f, 0.f, 1.f);
// Draw the cube
glDrawArrays(GL_TRIANGLES, 0, 36);
// Finally, display the rendered frame on screen
window.display();
}
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window.hpp>
#include <SFML/OpenGL.hpp>
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Request a 32-bits depth buffer when creating the window
sf::ContextSettings contextSettings;
contextSettings.depthBits = 32;
// Create the main window
sf::Window window(sf::VideoMode(640, 480), "SFML window with OpenGL", sf::Style::Default, contextSettings);
// Make it the active window for OpenGL calls
window.setActive();
// Set the color and depth clear values
glClearDepth(1.f);
glClearColor(0.f, 0.f, 0.f, 1.f);
// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
// Disable lighting and texturing
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
// Configure the viewport (the same size as the window)
glViewport(0, 0, window.getSize().x, window.getSize().y);
// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GLfloat ratio = static_cast<float>(window.getSize().x) / window.getSize().y;
glFrustum(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);
// Define a 3D cube (6 faces made of 2 triangles composed by 3 vertices)
GLfloat cube[] =
{
// positions // colors (r, g, b, a)
-50, -50, -50, 0, 0, 1, 1,
-50, 50, -50, 0, 0, 1, 1,
-50, -50, 50, 0, 0, 1, 1,
-50, -50, 50, 0, 0, 1, 1,
-50, 50, -50, 0, 0, 1, 1,
-50, 50, 50, 0, 0, 1, 1,
50, -50, -50, 0, 1, 0, 1,
50, 50, -50, 0, 1, 0, 1,
50, -50, 50, 0, 1, 0, 1,
50, -50, 50, 0, 1, 0, 1,
50, 50, -50, 0, 1, 0, 1,
50, 50, 50, 0, 1, 0, 1,
-50, -50, -50, 1, 0, 0, 1,
50, -50, -50, 1, 0, 0, 1,
-50, -50, 50, 1, 0, 0, 1,
-50, -50, 50, 1, 0, 0, 1,
50, -50, -50, 1, 0, 0, 1,
50, -50, 50, 1, 0, 0, 1,
-50, 50, -50, 0, 1, 1, 1,
50, 50, -50, 0, 1, 1, 1,
-50, 50, 50, 0, 1, 1, 1,
-50, 50, 50, 0, 1, 1, 1,
50, 50, -50, 0, 1, 1, 1,
50, 50, 50, 0, 1, 1, 1,
-50, -50, -50, 1, 0, 1, 1,
50, -50, -50, 1, 0, 1, 1,
-50, 50, -50, 1, 0, 1, 1,
-50, 50, -50, 1, 0, 1, 1,
50, -50, -50, 1, 0, 1, 1,
50, 50, -50, 1, 0, 1, 1,
-50, -50, 50, 1, 1, 0, 1,
50, -50, 50, 1, 1, 0, 1,
-50, 50, 50, 1, 1, 0, 1,
-50, 50, 50, 1, 1, 0, 1,
50, -50, 50, 1, 1, 0, 1,
50, 50, 50, 1, 1, 0, 1,
};
// Enable position and color vertex components
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 7 * sizeof(GLfloat), cube);
glColorPointer(4, GL_FLOAT, 7 * sizeof(GLfloat), cube + 3);
// Disable normal and texture coordinates vertex components
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// Create a clock for measuring the time elapsed
sf::Clock clock;
// Start the game loop
while (window.isOpen())
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::Closed)
window.close();
// Escape key: exit
if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
window.close();
// Resize event: adjust the viewport
if (event.type == sf::Event::Resized)
glViewport(0, 0, event.size.width, event.size.height);
}
// Clear the color and depth buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Apply some transformations to rotate the cube
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.f, 0.f, -200.f);
glRotatef(clock.getElapsedTime().asSeconds() * 50, 1.f, 0.f, 0.f);
glRotatef(clock.getElapsedTime().asSeconds() * 30, 0.f, 1.f, 0.f);
glRotatef(clock.getElapsedTime().asSeconds() * 90, 0.f, 0.f, 1.f);
// Draw the cube
glDrawArrays(GL_TRIANGLES, 0, 36);
// Finally, display the rendered frame on screen
window.display();
}
return EXIT_SUCCESS;
}

View file

@ -1,50 +1,50 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_AUDIO_HPP
#define SFML_AUDIO_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System.hpp>
#include <SFML/Audio/Listener.hpp>
#include <SFML/Audio/Music.hpp>
#include <SFML/Audio/Sound.hpp>
#include <SFML/Audio/SoundBuffer.hpp>
#include <SFML/Audio/SoundBufferRecorder.hpp>
#include <SFML/Audio/SoundRecorder.hpp>
#include <SFML/Audio/SoundStream.hpp>
#endif // SFML_AUDIO_HPP
////////////////////////////////////////////////////////////
/// \defgroup audio Audio module
///
/// Sounds, streaming (musics or custom sources), recording,
/// spatialization.
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_AUDIO_HPP
#define SFML_AUDIO_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System.hpp>
#include <SFML/Audio/Listener.hpp>
#include <SFML/Audio/Music.hpp>
#include <SFML/Audio/Sound.hpp>
#include <SFML/Audio/SoundBuffer.hpp>
#include <SFML/Audio/SoundBufferRecorder.hpp>
#include <SFML/Audio/SoundRecorder.hpp>
#include <SFML/Audio/SoundStream.hpp>
#endif // SFML_AUDIO_HPP
////////////////////////////////////////////////////////////
/// \defgroup audio Audio module
///
/// Sounds, streaming (musics or custom sources), recording,
/// spatialization.
///
////////////////////////////////////////////////////////////

View file

@ -1,234 +1,234 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_LISTENER_HPP
#define SFML_LISTENER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/System/Vector3.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief The audio listener is the point in the scene
/// from where all the sounds are heard
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API Listener
{
public :
////////////////////////////////////////////////////////////
/// \brief Change the global volume of all the sounds and musics
///
/// The volume is a number between 0 and 100; it is combined with
/// the individual volume of each sound / music.
/// The default value for the volume is 100 (maximum).
///
/// \param volume New global volume, in the range [0, 100]
///
/// \see getGlobalVolume
///
////////////////////////////////////////////////////////////
static void setGlobalVolume(float volume);
////////////////////////////////////////////////////////////
/// \brief Get the current value of the global volume
///
/// \return Current global volume, in the range [0, 100]
///
/// \see setGlobalVolume
///
////////////////////////////////////////////////////////////
static float getGlobalVolume();
////////////////////////////////////////////////////////////
/// \brief Set the position of the listener in the scene
///
/// The default listener's position is (0, 0, 0).
///
/// \param x X coordinate of the listener's position
/// \param y Y coordinate of the listener's position
/// \param z Z coordinate of the listener's position
///
/// \see getPosition, setDirection
///
////////////////////////////////////////////////////////////
static void setPosition(float x, float y, float z);
////////////////////////////////////////////////////////////
/// \brief Set the position of the listener in the scene
///
/// The default listener's position is (0, 0, 0).
///
/// \param position New listener's position
///
/// \see getPosition, setDirection
///
////////////////////////////////////////////////////////////
static void setPosition(const Vector3f& position);
////////////////////////////////////////////////////////////
/// \brief Get the current position of the listener in the scene
///
/// \return Listener's position
///
/// \see setPosition
///
////////////////////////////////////////////////////////////
static Vector3f getPosition();
////////////////////////////////////////////////////////////
/// \brief Set the forward vector of the listener in the scene
///
/// The direction (also called "at vector") is the vector
/// pointing forward from the listener's perspective. Together
/// with the up vector, it defines the 3D orientation of the
/// listener in the scene. The direction vector doesn't
/// have to be normalized.
/// The default listener's direction is (0, 0, -1).
///
/// \param x X coordinate of the listener's direction
/// \param y Y coordinate of the listener's direction
/// \param z Z coordinate of the listener's direction
///
/// \see getDirection, setUpVector, setPosition
///
////////////////////////////////////////////////////////////
static void setDirection(float x, float y, float z);
////////////////////////////////////////////////////////////
/// \brief Set the forward vector of the listener in the scene
///
/// The direction (also called "at vector") is the vector
/// pointing forward from the listener's perspective. Together
/// with the up vector, it defines the 3D orientation of the
/// listener in the scene. The direction vector doesn't
/// have to be normalized.
/// The default listener's direction is (0, 0, -1).
///
/// \param direction New listener's direction
///
/// \see getDirection, setUpVector, setPosition
///
////////////////////////////////////////////////////////////
static void setDirection(const Vector3f& direction);
////////////////////////////////////////////////////////////
/// \brief Get the current forward vector of the listener in the scene
///
/// \return Listener's forward vector (not normalized)
///
/// \see setDirection
///
////////////////////////////////////////////////////////////
static Vector3f getDirection();
////////////////////////////////////////////////////////////
/// \brief Set the upward vector of the listener in the scene
///
/// The up vector is the vector that points upward from the
/// listener's perspective. Together with the direction, it
/// defines the 3D orientation of the listener in the scene.
/// The up vector doesn't have to be normalized.
/// The default listener's up vector is (0, 1, 0). It is usually
/// not necessary to change it, especially in 2D scenarios.
///
/// \param x X coordinate of the listener's up vector
/// \param y Y coordinate of the listener's up vector
/// \param z Z coordinate of the listener's up vector
///
/// \see getUpVector, setDirection, setPosition
///
////////////////////////////////////////////////////////////
static void setUpVector(float x, float y, float z);
////////////////////////////////////////////////////////////
/// \brief Set the upward vector of the listener in the scene
///
/// The up vector is the vector that points upward from the
/// listener's perspective. Together with the direction, it
/// defines the 3D orientation of the listener in the scene.
/// The up vector doesn't have to be normalized.
/// The default listener's up vector is (0, 1, 0). It is usually
/// not necessary to change it, especially in 2D scenarios.
///
/// \param upVector New listener's up vector
///
/// \see getUpVector, setDirection, setPosition
///
////////////////////////////////////////////////////////////
static void setUpVector(const Vector3f& upVector);
////////////////////////////////////////////////////////////
/// \brief Get the current upward vector of the listener in the scene
///
/// \return Listener's upward vector (not normalized)
///
/// \see setUpVector
///
////////////////////////////////////////////////////////////
static Vector3f getUpVector();
};
} // namespace sf
#endif // SFML_LISTENER_HPP
////////////////////////////////////////////////////////////
/// \class sf::Listener
/// \ingroup audio
///
/// The audio listener defines the global properties of the
/// audio environment, it defines where and how sounds and musics
/// are heard. If sf::View is the eyes of the user, then sf::Listener
/// is his ears (by the way, they are often linked together --
/// same position, orientation, etc.).
///
/// sf::Listener is a simple interface, which allows to setup the
/// listener in the 3D audio environment (position, direction and
/// up vector), and to adjust the global volume.
///
/// Because the listener is unique in the scene, sf::Listener only
/// contains static functions and doesn't have to be instantiated.
///
/// Usage example:
/// \code
/// // Move the listener to the position (1, 0, -5)
/// sf::Listener::setPosition(1, 0, -5);
///
/// // Make it face the right axis (1, 0, 0)
/// sf::Listener::setDirection(1, 0, 0);
///
/// // Reduce the global volume
/// sf::Listener::setGlobalVolume(50);
/// \endcode
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_LISTENER_HPP
#define SFML_LISTENER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/System/Vector3.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief The audio listener is the point in the scene
/// from where all the sounds are heard
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API Listener
{
public:
////////////////////////////////////////////////////////////
/// \brief Change the global volume of all the sounds and musics
///
/// The volume is a number between 0 and 100; it is combined with
/// the individual volume of each sound / music.
/// The default value for the volume is 100 (maximum).
///
/// \param volume New global volume, in the range [0, 100]
///
/// \see getGlobalVolume
///
////////////////////////////////////////////////////////////
static void setGlobalVolume(float volume);
////////////////////////////////////////////////////////////
/// \brief Get the current value of the global volume
///
/// \return Current global volume, in the range [0, 100]
///
/// \see setGlobalVolume
///
////////////////////////////////////////////////////////////
static float getGlobalVolume();
////////////////////////////////////////////////////////////
/// \brief Set the position of the listener in the scene
///
/// The default listener's position is (0, 0, 0).
///
/// \param x X coordinate of the listener's position
/// \param y Y coordinate of the listener's position
/// \param z Z coordinate of the listener's position
///
/// \see getPosition, setDirection
///
////////////////////////////////////////////////////////////
static void setPosition(float x, float y, float z);
////////////////////////////////////////////////////////////
/// \brief Set the position of the listener in the scene
///
/// The default listener's position is (0, 0, 0).
///
/// \param position New listener's position
///
/// \see getPosition, setDirection
///
////////////////////////////////////////////////////////////
static void setPosition(const Vector3f& position);
////////////////////////////////////////////////////////////
/// \brief Get the current position of the listener in the scene
///
/// \return Listener's position
///
/// \see setPosition
///
////////////////////////////////////////////////////////////
static Vector3f getPosition();
////////////////////////////////////////////////////////////
/// \brief Set the forward vector of the listener in the scene
///
/// The direction (also called "at vector") is the vector
/// pointing forward from the listener's perspective. Together
/// with the up vector, it defines the 3D orientation of the
/// listener in the scene. The direction vector doesn't
/// have to be normalized.
/// The default listener's direction is (0, 0, -1).
///
/// \param x X coordinate of the listener's direction
/// \param y Y coordinate of the listener's direction
/// \param z Z coordinate of the listener's direction
///
/// \see getDirection, setUpVector, setPosition
///
////////////////////////////////////////////////////////////
static void setDirection(float x, float y, float z);
////////////////////////////////////////////////////////////
/// \brief Set the forward vector of the listener in the scene
///
/// The direction (also called "at vector") is the vector
/// pointing forward from the listener's perspective. Together
/// with the up vector, it defines the 3D orientation of the
/// listener in the scene. The direction vector doesn't
/// have to be normalized.
/// The default listener's direction is (0, 0, -1).
///
/// \param direction New listener's direction
///
/// \see getDirection, setUpVector, setPosition
///
////////////////////////////////////////////////////////////
static void setDirection(const Vector3f& direction);
////////////////////////////////////////////////////////////
/// \brief Get the current forward vector of the listener in the scene
///
/// \return Listener's forward vector (not normalized)
///
/// \see setDirection
///
////////////////////////////////////////////////////////////
static Vector3f getDirection();
////////////////////////////////////////////////////////////
/// \brief Set the upward vector of the listener in the scene
///
/// The up vector is the vector that points upward from the
/// listener's perspective. Together with the direction, it
/// defines the 3D orientation of the listener in the scene.
/// The up vector doesn't have to be normalized.
/// The default listener's up vector is (0, 1, 0). It is usually
/// not necessary to change it, especially in 2D scenarios.
///
/// \param x X coordinate of the listener's up vector
/// \param y Y coordinate of the listener's up vector
/// \param z Z coordinate of the listener's up vector
///
/// \see getUpVector, setDirection, setPosition
///
////////////////////////////////////////////////////////////
static void setUpVector(float x, float y, float z);
////////////////////////////////////////////////////////////
/// \brief Set the upward vector of the listener in the scene
///
/// The up vector is the vector that points upward from the
/// listener's perspective. Together with the direction, it
/// defines the 3D orientation of the listener in the scene.
/// The up vector doesn't have to be normalized.
/// The default listener's up vector is (0, 1, 0). It is usually
/// not necessary to change it, especially in 2D scenarios.
///
/// \param upVector New listener's up vector
///
/// \see getUpVector, setDirection, setPosition
///
////////////////////////////////////////////////////////////
static void setUpVector(const Vector3f& upVector);
////////////////////////////////////////////////////////////
/// \brief Get the current upward vector of the listener in the scene
///
/// \return Listener's upward vector (not normalized)
///
/// \see setUpVector
///
////////////////////////////////////////////////////////////
static Vector3f getUpVector();
};
} // namespace sf
#endif // SFML_LISTENER_HPP
////////////////////////////////////////////////////////////
/// \class sf::Listener
/// \ingroup audio
///
/// The audio listener defines the global properties of the
/// audio environment, it defines where and how sounds and musics
/// are heard. If sf::View is the eyes of the user, then sf::Listener
/// is his ears (by the way, they are often linked together --
/// same position, orientation, etc.).
///
/// sf::Listener is a simple interface, which allows to setup the
/// listener in the 3D audio environment (position, direction and
/// up vector), and to adjust the global volume.
///
/// Because the listener is unique in the scene, sf::Listener only
/// contains static functions and doesn't have to be instantiated.
///
/// Usage example:
/// \code
/// // Move the listener to the position (1, 0, -5)
/// sf::Listener::setPosition(1, 0, -5);
///
/// // Make it face the right axis (1, 0, 0)
/// sf::Listener::setDirection(1, 0, 0);
///
/// // Reduce the global volume
/// sf::Listener::setGlobalVolume(50);
/// \endcode
///
////////////////////////////////////////////////////////////

View file

@ -1,228 +1,228 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_MUSIC_HPP
#define SFML_MUSIC_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/Audio/SoundStream.hpp>
#include <SFML/System/Mutex.hpp>
#include <SFML/System/Time.hpp>
#include <string>
#include <vector>
namespace sf
{
namespace priv
{
class SoundFile;
}
class InputStream;
////////////////////////////////////////////////////////////
/// \brief Streamed music played from an audio file
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API Music : public SoundStream
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Music();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~Music();
////////////////////////////////////////////////////////////
/// \brief Open a music from an audio file
///
/// This function doesn't start playing the music (call play()
/// to do so).
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
///
/// \param filename Path of the music file to open
///
/// \return True if loading succeeded, false if it failed
///
/// \see openFromMemory, openFromStream
///
////////////////////////////////////////////////////////////
bool openFromFile(const std::string& filename);
////////////////////////////////////////////////////////////
/// \brief Open a music from an audio file in memory
///
/// This function doesn't start playing the music (call play()
/// to do so).
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
/// Since the music is not loaded completely but rather streamed
/// continuously, the \a data must remain available as long as the
/// music is playing (ie. you can't deallocate it right after calling
/// this function).
///
/// \param data Pointer to the file data in memory
/// \param sizeInBytes Size of the data to load, in bytes
///
/// \return True if loading succeeded, false if it failed
///
/// \see openFromFile, openFromStream
///
////////////////////////////////////////////////////////////
bool openFromMemory(const void* data, std::size_t sizeInBytes);
////////////////////////////////////////////////////////////
/// \brief Open a music from an audio file in a custom stream
///
/// This function doesn't start playing the music (call play()
/// to do so).
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
/// Since the music is not loaded completely but rather streamed
/// continuously, the \a stream must remain alive as long as the
/// music is playing (ie. you can't destroy it right after calling
/// this function).
///
/// \param stream Source stream to read from
///
/// \return True if loading succeeded, false if it failed
///
/// \see openFromFile, openFromMemory
///
////////////////////////////////////////////////////////////
bool openFromStream(InputStream& stream);
////////////////////////////////////////////////////////////
/// \brief Get the total duration of the music
///
/// \return Music duration
///
////////////////////////////////////////////////////////////
Time getDuration() const;
protected :
////////////////////////////////////////////////////////////
/// \brief Request a new chunk of audio samples from the stream source
///
/// This function fills the chunk from the next samples
/// to read from the audio file.
///
/// \param data Chunk of data to fill
///
/// \return True to continue playback, false to stop
///
////////////////////////////////////////////////////////////
virtual bool onGetData(Chunk& data);
////////////////////////////////////////////////////////////
/// \brief Change the current playing position in the stream source
///
/// \param timeOffset New playing position, from the beginning of the music
///
////////////////////////////////////////////////////////////
virtual void onSeek(Time timeOffset);
private :
////////////////////////////////////////////////////////////
/// \brief Initialize the internal state after loading a new music
///
////////////////////////////////////////////////////////////
void initialize();
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
priv::SoundFile* m_file; ///< Sound file
Time m_duration; ///< Music duration
std::vector<Int16> m_samples; ///< Temporary buffer of samples
Mutex m_mutex; ///< Mutex protecting the data
};
} // namespace sf
#endif // SFML_MUSIC_HPP
////////////////////////////////////////////////////////////
/// \class sf::Music
/// \ingroup audio
///
/// Musics are sounds that are streamed rather than completely
/// loaded in memory. This is especially useful for compressed
/// musics that usually take hundreds of MB when they are
/// uncompressed: by streaming it instead of loading it entirely,
/// you avoid saturating the memory and have almost no loading delay.
///
/// Apart from that, a sf::Music has almost the same features as
/// the sf::SoundBuffer / sf::Sound pair: you can play/pause/stop
/// it, request its parameters (channels, sample rate), change
/// the way it is played (pitch, volume, 3D position, ...), etc.
///
/// As a sound stream, a music is played in its own thread in order
/// not to block the rest of the program. This means that you can
/// leave the music alone after calling play(), it will manage itself
/// very well.
///
/// Usage example:
/// \code
/// // Declare a new music
/// sf::Music music;
///
/// // Open it from an audio file
/// if (!music.openFromFile("music.ogg"))
/// {
/// // error...
/// }
///
/// // Change some parameters
/// music.setPosition(0, 1, 10); // change its 3D position
/// music.setPitch(2); // increase the pitch
/// music.setVolume(50); // reduce the volume
/// music.setLoop(true); // make it loop
///
/// // Play it
/// music.play();
/// \endcode
///
/// \see sf::Sound, sf::SoundStream
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_MUSIC_HPP
#define SFML_MUSIC_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/Audio/SoundStream.hpp>
#include <SFML/System/Mutex.hpp>
#include <SFML/System/Time.hpp>
#include <string>
#include <vector>
namespace sf
{
namespace priv
{
class SoundFile;
}
class InputStream;
////////////////////////////////////////////////////////////
/// \brief Streamed music played from an audio file
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API Music : public SoundStream
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Music();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~Music();
////////////////////////////////////////////////////////////
/// \brief Open a music from an audio file
///
/// This function doesn't start playing the music (call play()
/// to do so).
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
///
/// \param filename Path of the music file to open
///
/// \return True if loading succeeded, false if it failed
///
/// \see openFromMemory, openFromStream
///
////////////////////////////////////////////////////////////
bool openFromFile(const std::string& filename);
////////////////////////////////////////////////////////////
/// \brief Open a music from an audio file in memory
///
/// This function doesn't start playing the music (call play()
/// to do so).
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
/// Since the music is not loaded completely but rather streamed
/// continuously, the \a data must remain available as long as the
/// music is playing (ie. you can't deallocate it right after calling
/// this function).
///
/// \param data Pointer to the file data in memory
/// \param sizeInBytes Size of the data to load, in bytes
///
/// \return True if loading succeeded, false if it failed
///
/// \see openFromFile, openFromStream
///
////////////////////////////////////////////////////////////
bool openFromMemory(const void* data, std::size_t sizeInBytes);
////////////////////////////////////////////////////////////
/// \brief Open a music from an audio file in a custom stream
///
/// This function doesn't start playing the music (call play()
/// to do so).
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
/// Since the music is not loaded completely but rather streamed
/// continuously, the \a stream must remain alive as long as the
/// music is playing (ie. you can't destroy it right after calling
/// this function).
///
/// \param stream Source stream to read from
///
/// \return True if loading succeeded, false if it failed
///
/// \see openFromFile, openFromMemory
///
////////////////////////////////////////////////////////////
bool openFromStream(InputStream& stream);
////////////////////////////////////////////////////////////
/// \brief Get the total duration of the music
///
/// \return Music duration
///
////////////////////////////////////////////////////////////
Time getDuration() const;
protected:
////////////////////////////////////////////////////////////
/// \brief Request a new chunk of audio samples from the stream source
///
/// This function fills the chunk from the next samples
/// to read from the audio file.
///
/// \param data Chunk of data to fill
///
/// \return True to continue playback, false to stop
///
////////////////////////////////////////////////////////////
virtual bool onGetData(Chunk& data);
////////////////////////////////////////////////////////////
/// \brief Change the current playing position in the stream source
///
/// \param timeOffset New playing position, from the beginning of the music
///
////////////////////////////////////////////////////////////
virtual void onSeek(Time timeOffset);
private:
////////////////////////////////////////////////////////////
/// \brief Initialize the internal state after loading a new music
///
////////////////////////////////////////////////////////////
void initialize();
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
priv::SoundFile* m_file; ///< Sound file
Time m_duration; ///< Music duration
std::vector<Int16> m_samples; ///< Temporary buffer of samples
Mutex m_mutex; ///< Mutex protecting the data
};
} // namespace sf
#endif // SFML_MUSIC_HPP
////////////////////////////////////////////////////////////
/// \class sf::Music
/// \ingroup audio
///
/// Musics are sounds that are streamed rather than completely
/// loaded in memory. This is especially useful for compressed
/// musics that usually take hundreds of MB when they are
/// uncompressed: by streaming it instead of loading it entirely,
/// you avoid saturating the memory and have almost no loading delay.
///
/// Apart from that, a sf::Music has almost the same features as
/// the sf::SoundBuffer / sf::Sound pair: you can play/pause/stop
/// it, request its parameters (channels, sample rate), change
/// the way it is played (pitch, volume, 3D position, ...), etc.
///
/// As a sound stream, a music is played in its own thread in order
/// not to block the rest of the program. This means that you can
/// leave the music alone after calling play(), it will manage itself
/// very well.
///
/// Usage example:
/// \code
/// // Declare a new music
/// sf::Music music;
///
/// // Open it from an audio file
/// if (!music.openFromFile("music.ogg"))
/// {
/// // error...
/// }
///
/// // Change some parameters
/// music.setPosition(0, 1, 10); // change its 3D position
/// music.setPitch(2); // increase the pitch
/// music.setVolume(50); // reduce the volume
/// music.setLoop(true); // make it loop
///
/// // Play it
/// music.play();
/// \endcode
///
/// \see sf::Sound, sf::SoundStream
///
////////////////////////////////////////////////////////////

View file

@ -1,264 +1,264 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUND_HPP
#define SFML_SOUND_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/Audio/SoundSource.hpp>
#include <SFML/System/Time.hpp>
#include <cstdlib>
namespace sf
{
class SoundBuffer;
////////////////////////////////////////////////////////////
/// \brief Regular sound that can be played in the audio environment
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API Sound : public SoundSource
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Sound();
////////////////////////////////////////////////////////////
/// \brief Construct the sound with a buffer
///
/// \param buffer Sound buffer containing the audio data to play with the sound
///
////////////////////////////////////////////////////////////
explicit Sound(const SoundBuffer& buffer);
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
Sound(const Sound& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~Sound();
////////////////////////////////////////////////////////////
/// \brief Start or resume playing the sound
///
/// This function starts the stream if it was stopped, resumes
/// it if it was paused, and restarts it from beginning if it
/// was it already playing.
/// This function uses its own thread so that it doesn't block
/// the rest of the program while the sound is played.
///
/// \see pause, stop
///
////////////////////////////////////////////////////////////
void play();
////////////////////////////////////////////////////////////
/// \brief Pause the sound
///
/// This function pauses the sound if it was playing,
/// otherwise (sound already paused or stopped) it has no effect.
///
/// \see play, stop
///
////////////////////////////////////////////////////////////
void pause();
////////////////////////////////////////////////////////////
/// \brief stop playing the sound
///
/// This function stops the sound if it was playing or paused,
/// and does nothing if it was already stopped.
/// It also resets the playing position (unlike pause()).
///
/// \see play, pause
///
////////////////////////////////////////////////////////////
void stop();
////////////////////////////////////////////////////////////
/// \brief Set the source buffer containing the audio data to play
///
/// It is important to note that the sound buffer is not copied,
/// thus the sf::SoundBuffer instance must remain alive as long
/// as it is attached to the sound.
///
/// \param buffer Sound buffer to attach to the sound
///
/// \see getBuffer
///
////////////////////////////////////////////////////////////
void setBuffer(const SoundBuffer& buffer);
////////////////////////////////////////////////////////////
/// \brief Set whether or not the sound should loop after reaching the end
///
/// If set, the sound will restart from beginning after
/// reaching the end and so on, until it is stopped or
/// setLoop(false) is called.
/// The default looping state for sound is false.
///
/// \param loop True to play in loop, false to play once
///
/// \see getLoop
///
////////////////////////////////////////////////////////////
void setLoop(bool loop);
////////////////////////////////////////////////////////////
/// \brief Change the current playing position of the sound
///
/// The playing position can be changed when the sound is
/// either paused or playing. Changing the playing position
/// when the sound is stopped has no effect, since playing
/// the sound would reset its position.
///
/// \param timeOffset New playing position, from the beginning of the sound
///
/// \see getPlayingOffset
///
////////////////////////////////////////////////////////////
void setPlayingOffset(Time timeOffset);
////////////////////////////////////////////////////////////
/// \brief Get the audio buffer attached to the sound
///
/// \return Sound buffer attached to the sound (can be NULL)
///
////////////////////////////////////////////////////////////
const SoundBuffer* getBuffer() const;
////////////////////////////////////////////////////////////
/// \brief Tell whether or not the sound is in loop mode
///
/// \return True if the sound is looping, false otherwise
///
/// \see setLoop
///
////////////////////////////////////////////////////////////
bool getLoop() const;
////////////////////////////////////////////////////////////
/// \brief Get the current playing position of the sound
///
/// \return Current playing position, from the beginning of the sound
///
/// \see setPlayingOffset
///
////////////////////////////////////////////////////////////
Time getPlayingOffset() const;
////////////////////////////////////////////////////////////
/// \brief Get the current status of the sound (stopped, paused, playing)
///
/// \return Current status of the sound
///
////////////////////////////////////////////////////////////
Status getStatus() const;
////////////////////////////////////////////////////////////
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
Sound& operator =(const Sound& right);
////////////////////////////////////////////////////////////
/// \brief Reset the internal buffer of the sound
///
/// This function is for internal use only, you don't have
/// to use it. It is called by the sf::SoundBuffer that
/// this sound uses, when it is destroyed in order to prevent
/// the sound from using a dead buffer.
///
////////////////////////////////////////////////////////////
void resetBuffer();
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
const SoundBuffer* m_buffer; ///< Sound buffer bound to the source
};
} // namespace sf
#endif // SFML_SOUND_HPP
////////////////////////////////////////////////////////////
/// \class sf::Sound
/// \ingroup audio
///
/// sf::Sound is the class to use to play sounds.
/// It provides:
/// \li Control (play, pause, stop)
/// \li Ability to modify output parameters in real-time (pitch, volume, ...)
/// \li 3D spatial features (position, attenuation, ...).
///
/// sf::Sound is perfect for playing short sounds that can
/// fit in memory and require no latency, like foot steps or
/// gun shots. For longer sounds, like background musics
/// or long speeches, rather see sf::Music (which is based
/// on streaming).
///
/// In order to work, a sound must be given a buffer of audio
/// data to play. Audio data (samples) is stored in sf::SoundBuffer,
/// and attached to a sound with the setBuffer() function.
/// The buffer object attached to a sound must remain alive
/// as long as the sound uses it. Note that multiple sounds
/// can use the same sound buffer at the same time.
///
/// Usage example:
/// \code
/// sf::SoundBuffer buffer;
/// buffer.loadFromFile("sound.wav");
///
/// sf::Sound sound;
/// sound.setBuffer(buffer);
/// sound.play();
/// \endcode
///
/// \see sf::SoundBuffer, sf::Music
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUND_HPP
#define SFML_SOUND_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/Audio/SoundSource.hpp>
#include <SFML/System/Time.hpp>
#include <cstdlib>
namespace sf
{
class SoundBuffer;
////////////////////////////////////////////////////////////
/// \brief Regular sound that can be played in the audio environment
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API Sound : public SoundSource
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Sound();
////////////////////////////////////////////////////////////
/// \brief Construct the sound with a buffer
///
/// \param buffer Sound buffer containing the audio data to play with the sound
///
////////////////////////////////////////////////////////////
explicit Sound(const SoundBuffer& buffer);
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
Sound(const Sound& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~Sound();
////////////////////////////////////////////////////////////
/// \brief Start or resume playing the sound
///
/// This function starts the stream if it was stopped, resumes
/// it if it was paused, and restarts it from beginning if it
/// was it already playing.
/// This function uses its own thread so that it doesn't block
/// the rest of the program while the sound is played.
///
/// \see pause, stop
///
////////////////////////////////////////////////////////////
void play();
////////////////////////////////////////////////////////////
/// \brief Pause the sound
///
/// This function pauses the sound if it was playing,
/// otherwise (sound already paused or stopped) it has no effect.
///
/// \see play, stop
///
////////////////////////////////////////////////////////////
void pause();
////////////////////////////////////////////////////////////
/// \brief stop playing the sound
///
/// This function stops the sound if it was playing or paused,
/// and does nothing if it was already stopped.
/// It also resets the playing position (unlike pause()).
///
/// \see play, pause
///
////////////////////////////////////////////////////////////
void stop();
////////////////////////////////////////////////////////////
/// \brief Set the source buffer containing the audio data to play
///
/// It is important to note that the sound buffer is not copied,
/// thus the sf::SoundBuffer instance must remain alive as long
/// as it is attached to the sound.
///
/// \param buffer Sound buffer to attach to the sound
///
/// \see getBuffer
///
////////////////////////////////////////////////////////////
void setBuffer(const SoundBuffer& buffer);
////////////////////////////////////////////////////////////
/// \brief Set whether or not the sound should loop after reaching the end
///
/// If set, the sound will restart from beginning after
/// reaching the end and so on, until it is stopped or
/// setLoop(false) is called.
/// The default looping state for sound is false.
///
/// \param loop True to play in loop, false to play once
///
/// \see getLoop
///
////////////////////////////////////////////////////////////
void setLoop(bool loop);
////////////////////////////////////////////////////////////
/// \brief Change the current playing position of the sound
///
/// The playing position can be changed when the sound is
/// either paused or playing. Changing the playing position
/// when the sound is stopped has no effect, since playing
/// the sound would reset its position.
///
/// \param timeOffset New playing position, from the beginning of the sound
///
/// \see getPlayingOffset
///
////////////////////////////////////////////////////////////
void setPlayingOffset(Time timeOffset);
////////////////////////////////////////////////////////////
/// \brief Get the audio buffer attached to the sound
///
/// \return Sound buffer attached to the sound (can be NULL)
///
////////////////////////////////////////////////////////////
const SoundBuffer* getBuffer() const;
////////////////////////////////////////////////////////////
/// \brief Tell whether or not the sound is in loop mode
///
/// \return True if the sound is looping, false otherwise
///
/// \see setLoop
///
////////////////////////////////////////////////////////////
bool getLoop() const;
////////////////////////////////////////////////////////////
/// \brief Get the current playing position of the sound
///
/// \return Current playing position, from the beginning of the sound
///
/// \see setPlayingOffset
///
////////////////////////////////////////////////////////////
Time getPlayingOffset() const;
////////////////////////////////////////////////////////////
/// \brief Get the current status of the sound (stopped, paused, playing)
///
/// \return Current status of the sound
///
////////////////////////////////////////////////////////////
Status getStatus() const;
////////////////////////////////////////////////////////////
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
Sound& operator =(const Sound& right);
////////////////////////////////////////////////////////////
/// \brief Reset the internal buffer of the sound
///
/// This function is for internal use only, you don't have
/// to use it. It is called by the sf::SoundBuffer that
/// this sound uses, when it is destroyed in order to prevent
/// the sound from using a dead buffer.
///
////////////////////////////////////////////////////////////
void resetBuffer();
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
const SoundBuffer* m_buffer; ///< Sound buffer bound to the source
};
} // namespace sf
#endif // SFML_SOUND_HPP
////////////////////////////////////////////////////////////
/// \class sf::Sound
/// \ingroup audio
///
/// sf::Sound is the class to use to play sounds.
/// It provides:
/// \li Control (play, pause, stop)
/// \li Ability to modify output parameters in real-time (pitch, volume, ...)
/// \li 3D spatial features (position, attenuation, ...).
///
/// sf::Sound is perfect for playing short sounds that can
/// fit in memory and require no latency, like foot steps or
/// gun shots. For longer sounds, like background musics
/// or long speeches, rather see sf::Music (which is based
/// on streaming).
///
/// In order to work, a sound must be given a buffer of audio
/// data to play. Audio data (samples) is stored in sf::SoundBuffer,
/// and attached to a sound with the setBuffer() function.
/// The buffer object attached to a sound must remain alive
/// as long as the sound uses it. Note that multiple sounds
/// can use the same sound buffer at the same time.
///
/// Usage example:
/// \code
/// sf::SoundBuffer buffer;
/// buffer.loadFromFile("sound.wav");
///
/// sf::Sound sound;
/// sound.setBuffer(buffer);
/// sound.play();
/// \endcode
///
/// \see sf::SoundBuffer, sf::Music
///
////////////////////////////////////////////////////////////

View file

@ -1,359 +1,359 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUNDBUFFER_HPP
#define SFML_SOUNDBUFFER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/System/Time.hpp>
#include <string>
#include <vector>
#include <set>
namespace sf
{
namespace priv
{
class SoundFile;
}
class Sound;
class InputStream;
////////////////////////////////////////////////////////////
/// \brief Storage for audio samples defining a sound
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API SoundBuffer
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
SoundBuffer();
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
SoundBuffer(const SoundBuffer& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~SoundBuffer();
////////////////////////////////////////////////////////////
/// \brief Load the sound buffer from a file
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
///
/// \param filename Path of the sound file to load
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromMemory, loadFromStream, loadFromSamples, saveToFile
///
////////////////////////////////////////////////////////////
bool loadFromFile(const std::string& filename);
////////////////////////////////////////////////////////////
/// \brief Load the sound buffer from a file in memory
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
///
/// \param data Pointer to the file data in memory
/// \param sizeInBytes Size of the data to load, in bytes
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromFile, loadFromStream, loadFromSamples
///
////////////////////////////////////////////////////////////
bool loadFromMemory(const void* data, std::size_t sizeInBytes);
////////////////////////////////////////////////////////////
/// \brief Load the sound buffer from a custom stream
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
///
/// \param stream Source stream to read from
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromFile, loadFromMemory, loadFromSamples
///
////////////////////////////////////////////////////////////
bool loadFromStream(InputStream& stream);
////////////////////////////////////////////////////////////
/// \brief Load the sound buffer from an array of audio samples
///
/// The assumed format of the audio samples is 16 bits signed integer
/// (sf::Int16).
///
/// \param samples Pointer to the array of samples in memory
/// \param sampleCount Number of samples in the array
/// \param channelCount Number of channels (1 = mono, 2 = stereo, ...)
/// \param sampleRate Sample rate (number of samples to play per second)
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromFile, loadFromMemory, saveToFile
///
////////////////////////////////////////////////////////////
bool loadFromSamples(const Int16* samples, std::size_t sampleCount, unsigned int channelCount, unsigned int sampleRate);
////////////////////////////////////////////////////////////
/// \brief Save the sound buffer to an audio file
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
///
/// \param filename Path of the sound file to write
///
/// \return True if saving succeeded, false if it failed
///
/// \see loadFromFile, loadFromMemory, loadFromSamples
///
////////////////////////////////////////////////////////////
bool saveToFile(const std::string& filename) const;
////////////////////////////////////////////////////////////
/// \brief Get the array of audio samples stored in the buffer
///
/// The format of the returned samples is 16 bits signed integer
/// (sf::Int16). The total number of samples in this array
/// is given by the getSampleCount() function.
///
/// \return Read-only pointer to the array of sound samples
///
/// \see getSampleCount
///
////////////////////////////////////////////////////////////
const Int16* getSamples() const;
////////////////////////////////////////////////////////////
/// \brief Get the number of samples stored in the buffer
///
/// The array of samples can be accessed with the getSamples()
/// function.
///
/// \return Number of samples
///
/// \see getSamples
///
////////////////////////////////////////////////////////////
std::size_t getSampleCount() const;
////////////////////////////////////////////////////////////
/// \brief Get the sample rate of the sound
///
/// The sample rate is the number of samples played per second.
/// The higher, the better the quality (for example, 44100
/// samples/s is CD quality).
///
/// \return Sample rate (number of samples per second)
///
/// \see getChannelCount, getDuration
///
////////////////////////////////////////////////////////////
unsigned int getSampleRate() const;
////////////////////////////////////////////////////////////
/// \brief Get the number of channels used by the sound
///
/// If the sound is mono then the number of channels will
/// be 1, 2 for stereo, etc.
///
/// \return Number of channels
///
/// \see getSampleRate, getDuration
///
////////////////////////////////////////////////////////////
unsigned int getChannelCount() const;
////////////////////////////////////////////////////////////
/// \brief Get the total duration of the sound
///
/// \return Sound duration
///
/// \see getSampleRate, getChannelCount
///
////////////////////////////////////////////////////////////
Time getDuration() const;
////////////////////////////////////////////////////////////
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
SoundBuffer& operator =(const SoundBuffer& right);
private :
friend class Sound;
////////////////////////////////////////////////////////////
/// \brief Initialize the internal state after loading a new sound
///
/// \param file Sound file providing access to the new loaded sound
///
/// \return True on succesful initialization, false on failure
///
////////////////////////////////////////////////////////////
bool initialize(priv::SoundFile& file);
////////////////////////////////////////////////////////////
/// \brief Update the internal buffer with the cached audio samples
///
/// \param channelCount Number of channels
/// \param sampleRate Sample rate (number of samples per second)
///
/// \return True on success, false if any error happened
///
////////////////////////////////////////////////////////////
bool update(unsigned int channelCount, unsigned int sampleRate);
////////////////////////////////////////////////////////////
/// \brief Add a sound to the list of sounds that use this buffer
///
/// \param sound Sound instance to attach
///
////////////////////////////////////////////////////////////
void attachSound(Sound* sound) const;
////////////////////////////////////////////////////////////
/// \brief Remove a sound from the list of sounds that use this buffer
///
/// \param sound Sound instance to detach
///
////////////////////////////////////////////////////////////
void detachSound(Sound* sound) const;
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::set<Sound*> SoundList; ///< Set of unique sound instances
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
unsigned int m_buffer; ///< OpenAL buffer identifier
std::vector<Int16> m_samples; ///< Samples buffer
Time m_duration; ///< Sound duration
mutable SoundList m_sounds; ///< List of sounds that are using this buffer
};
} // namespace sf
#endif // SFML_SOUNDBUFFER_HPP
////////////////////////////////////////////////////////////
/// \class sf::SoundBuffer
/// \ingroup audio
///
/// A sound buffer holds the data of a sound, which is
/// an array of audio samples. A sample is a 16 bits signed integer
/// that defines the amplitude of the sound at a given time.
/// The sound is then restituted by playing these samples at
/// a high rate (for example, 44100 samples per second is the
/// standard rate used for playing CDs). In short, audio samples
/// are like texture pixels, and a sf::SoundBuffer is similar to
/// a sf::Texture.
///
/// A sound buffer can be loaded from a file (see loadFromFile()
/// for the complete list of supported formats), from memory, from
/// a custom stream (see sf::InputStream) or directly from an array
/// of samples. It can also be saved back to a file.
///
/// Sound buffers alone are not very useful: they hold the audio data
/// but cannot be played. To do so, you need to use the sf::Sound class,
/// which provides functions to play/pause/stop the sound as well as
/// changing the way it is outputted (volume, pitch, 3D position, ...).
/// This separation allows more flexibility and better performances:
/// indeed a sf::SoundBuffer is a heavy resource, and any operation on it
/// is slow (often too slow for real-time applications). On the other
/// side, a sf::Sound is a lightweight object, which can use the audio data
/// of a sound buffer and change the way it is played without actually
/// modifying that data. Note that it is also possible to bind
/// several sf::Sound instances to the same sf::SoundBuffer.
///
/// It is important to note that the sf::Sound instance doesn't
/// copy the buffer that it uses, it only keeps a reference to it.
/// Thus, a sf::SoundBuffer must not be destructed while it is
/// used by a sf::Sound (i.e. never write a function that
/// uses a local sf::SoundBuffer instance for loading a sound).
///
/// Usage example:
/// \code
/// // Declare a new sound buffer
/// sf::SoundBuffer buffer;
///
/// // Load it from a file
/// if (!buffer.loadFromFile("sound.wav"))
/// {
/// // error...
/// }
///
/// // Create a sound source and bind it to the buffer
/// sf::Sound sound1;
/// sound1.setBuffer(buffer);
///
/// // Play the sound
/// sound1.play();
///
/// // Create another sound source bound to the same buffer
/// sf::Sound sound2;
/// sound2.setBuffer(buffer);
///
/// // Play it with a higher pitch -- the first sound remains unchanged
/// sound2.setPitch(2);
/// sound2.play();
/// \endcode
///
/// \see sf::Sound, sf::SoundBufferRecorder
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUNDBUFFER_HPP
#define SFML_SOUNDBUFFER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/System/Time.hpp>
#include <string>
#include <vector>
#include <set>
namespace sf
{
namespace priv
{
class SoundFile;
}
class Sound;
class InputStream;
////////////////////////////////////////////////////////////
/// \brief Storage for audio samples defining a sound
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API SoundBuffer
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
SoundBuffer();
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
SoundBuffer(const SoundBuffer& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~SoundBuffer();
////////////////////////////////////////////////////////////
/// \brief Load the sound buffer from a file
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
///
/// \param filename Path of the sound file to load
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromMemory, loadFromStream, loadFromSamples, saveToFile
///
////////////////////////////////////////////////////////////
bool loadFromFile(const std::string& filename);
////////////////////////////////////////////////////////////
/// \brief Load the sound buffer from a file in memory
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
///
/// \param data Pointer to the file data in memory
/// \param sizeInBytes Size of the data to load, in bytes
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromFile, loadFromStream, loadFromSamples
///
////////////////////////////////////////////////////////////
bool loadFromMemory(const void* data, std::size_t sizeInBytes);
////////////////////////////////////////////////////////////
/// \brief Load the sound buffer from a custom stream
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
///
/// \param stream Source stream to read from
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromFile, loadFromMemory, loadFromSamples
///
////////////////////////////////////////////////////////////
bool loadFromStream(InputStream& stream);
////////////////////////////////////////////////////////////
/// \brief Load the sound buffer from an array of audio samples
///
/// The assumed format of the audio samples is 16 bits signed integer
/// (sf::Int16).
///
/// \param samples Pointer to the array of samples in memory
/// \param sampleCount Number of samples in the array
/// \param channelCount Number of channels (1 = mono, 2 = stereo, ...)
/// \param sampleRate Sample rate (number of samples to play per second)
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromFile, loadFromMemory, saveToFile
///
////////////////////////////////////////////////////////////
bool loadFromSamples(const Int16* samples, std::size_t sampleCount, unsigned int channelCount, unsigned int sampleRate);
////////////////////////////////////////////////////////////
/// \brief Save the sound buffer to an audio file
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
///
/// \param filename Path of the sound file to write
///
/// \return True if saving succeeded, false if it failed
///
/// \see loadFromFile, loadFromMemory, loadFromSamples
///
////////////////////////////////////////////////////////////
bool saveToFile(const std::string& filename) const;
////////////////////////////////////////////////////////////
/// \brief Get the array of audio samples stored in the buffer
///
/// The format of the returned samples is 16 bits signed integer
/// (sf::Int16). The total number of samples in this array
/// is given by the getSampleCount() function.
///
/// \return Read-only pointer to the array of sound samples
///
/// \see getSampleCount
///
////////////////////////////////////////////////////////////
const Int16* getSamples() const;
////////////////////////////////////////////////////////////
/// \brief Get the number of samples stored in the buffer
///
/// The array of samples can be accessed with the getSamples()
/// function.
///
/// \return Number of samples
///
/// \see getSamples
///
////////////////////////////////////////////////////////////
std::size_t getSampleCount() const;
////////////////////////////////////////////////////////////
/// \brief Get the sample rate of the sound
///
/// The sample rate is the number of samples played per second.
/// The higher, the better the quality (for example, 44100
/// samples/s is CD quality).
///
/// \return Sample rate (number of samples per second)
///
/// \see getChannelCount, getDuration
///
////////////////////////////////////////////////////////////
unsigned int getSampleRate() const;
////////////////////////////////////////////////////////////
/// \brief Get the number of channels used by the sound
///
/// If the sound is mono then the number of channels will
/// be 1, 2 for stereo, etc.
///
/// \return Number of channels
///
/// \see getSampleRate, getDuration
///
////////////////////////////////////////////////////////////
unsigned int getChannelCount() const;
////////////////////////////////////////////////////////////
/// \brief Get the total duration of the sound
///
/// \return Sound duration
///
/// \see getSampleRate, getChannelCount
///
////////////////////////////////////////////////////////////
Time getDuration() const;
////////////////////////////////////////////////////////////
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
SoundBuffer& operator =(const SoundBuffer& right);
private:
friend class Sound;
////////////////////////////////////////////////////////////
/// \brief Initialize the internal state after loading a new sound
///
/// \param file Sound file providing access to the new loaded sound
///
/// \return True on succesful initialization, false on failure
///
////////////////////////////////////////////////////////////
bool initialize(priv::SoundFile& file);
////////////////////////////////////////////////////////////
/// \brief Update the internal buffer with the cached audio samples
///
/// \param channelCount Number of channels
/// \param sampleRate Sample rate (number of samples per second)
///
/// \return True on success, false if any error happened
///
////////////////////////////////////////////////////////////
bool update(unsigned int channelCount, unsigned int sampleRate);
////////////////////////////////////////////////////////////
/// \brief Add a sound to the list of sounds that use this buffer
///
/// \param sound Sound instance to attach
///
////////////////////////////////////////////////////////////
void attachSound(Sound* sound) const;
////////////////////////////////////////////////////////////
/// \brief Remove a sound from the list of sounds that use this buffer
///
/// \param sound Sound instance to detach
///
////////////////////////////////////////////////////////////
void detachSound(Sound* sound) const;
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::set<Sound*> SoundList; ///< Set of unique sound instances
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
unsigned int m_buffer; ///< OpenAL buffer identifier
std::vector<Int16> m_samples; ///< Samples buffer
Time m_duration; ///< Sound duration
mutable SoundList m_sounds; ///< List of sounds that are using this buffer
};
} // namespace sf
#endif // SFML_SOUNDBUFFER_HPP
////////////////////////////////////////////////////////////
/// \class sf::SoundBuffer
/// \ingroup audio
///
/// A sound buffer holds the data of a sound, which is
/// an array of audio samples. A sample is a 16 bits signed integer
/// that defines the amplitude of the sound at a given time.
/// The sound is then restituted by playing these samples at
/// a high rate (for example, 44100 samples per second is the
/// standard rate used for playing CDs). In short, audio samples
/// are like texture pixels, and a sf::SoundBuffer is similar to
/// a sf::Texture.
///
/// A sound buffer can be loaded from a file (see loadFromFile()
/// for the complete list of supported formats), from memory, from
/// a custom stream (see sf::InputStream) or directly from an array
/// of samples. It can also be saved back to a file.
///
/// Sound buffers alone are not very useful: they hold the audio data
/// but cannot be played. To do so, you need to use the sf::Sound class,
/// which provides functions to play/pause/stop the sound as well as
/// changing the way it is outputted (volume, pitch, 3D position, ...).
/// This separation allows more flexibility and better performances:
/// indeed a sf::SoundBuffer is a heavy resource, and any operation on it
/// is slow (often too slow for real-time applications). On the other
/// side, a sf::Sound is a lightweight object, which can use the audio data
/// of a sound buffer and change the way it is played without actually
/// modifying that data. Note that it is also possible to bind
/// several sf::Sound instances to the same sf::SoundBuffer.
///
/// It is important to note that the sf::Sound instance doesn't
/// copy the buffer that it uses, it only keeps a reference to it.
/// Thus, a sf::SoundBuffer must not be destructed while it is
/// used by a sf::Sound (i.e. never write a function that
/// uses a local sf::SoundBuffer instance for loading a sound).
///
/// Usage example:
/// \code
/// // Declare a new sound buffer
/// sf::SoundBuffer buffer;
///
/// // Load it from a file
/// if (!buffer.loadFromFile("sound.wav"))
/// {
/// // error...
/// }
///
/// // Create a sound source and bind it to the buffer
/// sf::Sound sound1;
/// sound1.setBuffer(buffer);
///
/// // Play the sound
/// sound1.play();
///
/// // Create another sound source bound to the same buffer
/// sf::Sound sound2;
/// sound2.setBuffer(buffer);
///
/// // Play it with a higher pitch -- the first sound remains unchanged
/// sound2.setPitch(2);
/// sound2.play();
/// \endcode
///
/// \see sf::Sound, sf::SoundBufferRecorder
///
////////////////////////////////////////////////////////////

View file

@ -1,138 +1,138 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUNDBUFFERRECORDER_HPP
#define SFML_SOUNDBUFFERRECORDER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/Audio/SoundBuffer.hpp>
#include <SFML/Audio/SoundRecorder.hpp>
#include <vector>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Specialized SoundRecorder which stores the captured
/// audio data into a sound buffer
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API SoundBufferRecorder : public SoundRecorder
{
public :
////////////////////////////////////////////////////////////
/// \brief Get the sound buffer containing the captured audio data
///
/// The sound buffer is valid only after the capture has ended.
/// This function provides a read-only access to the internal
/// sound buffer, but it can be copied if you need to
/// make any modification to it.
///
/// \return Read-only access to the sound buffer
///
////////////////////////////////////////////////////////////
const SoundBuffer& getBuffer() const;
protected:
////////////////////////////////////////////////////////////
/// \brief Start capturing audio data
///
/// \return True to start the capture, or false to abort it
///
////////////////////////////////////////////////////////////
virtual bool onStart();
////////////////////////////////////////////////////////////
/// \brief Process a new chunk of recorded samples
///
/// \param samples Pointer to the new chunk of recorded samples
/// \param sampleCount Number of samples pointed by \a samples
///
/// \return True to continue the capture, or false to stop it
///
////////////////////////////////////////////////////////////
virtual bool onProcessSamples(const Int16* samples, std::size_t sampleCount);
////////////////////////////////////////////////////////////
/// \brief Stop capturing audio data
///
////////////////////////////////////////////////////////////
virtual void onStop();
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
std::vector<Int16> m_samples; ///< Temporary sample buffer to hold the recorded data
SoundBuffer m_buffer; ///< Sound buffer that will contain the recorded data
};
} // namespace sf
#endif // SFML_SOUNDBUFFERRECORDER_HPP
////////////////////////////////////////////////////////////
/// \class sf::SoundBufferRecorder
/// \ingroup audio
///
/// sf::SoundBufferRecorder allows to access a recorded sound
/// through a sf::SoundBuffer, so that it can be played, saved
/// to a file, etc.
///
/// It has the same simple interface as its base class (start(), stop())
/// and adds a function to retrieve the recorded sound buffer
/// (getBuffer()).
///
/// As usual, don't forget to call the isAvailable() function
/// before using this class (see sf::SoundRecorder for more details
/// about this).
///
/// Usage example:
/// \code
/// if (sf::SoundBufferRecorder::isAvailable())
/// {
/// // Record some audio data
/// sf::SoundBufferRecorder recorder;
/// recorder.start();
/// ...
/// recorder.stop();
///
/// // Get the buffer containing the captured audio data
/// const sf::SoundBuffer& buffer = recorder.getBuffer();
///
/// // Save it to a file (for example...)
/// buffer.saveToFile("my_record.ogg");
/// }
/// \endcode
///
/// \see sf::SoundRecorder
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUNDBUFFERRECORDER_HPP
#define SFML_SOUNDBUFFERRECORDER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/Audio/SoundBuffer.hpp>
#include <SFML/Audio/SoundRecorder.hpp>
#include <vector>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Specialized SoundRecorder which stores the captured
/// audio data into a sound buffer
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API SoundBufferRecorder : public SoundRecorder
{
public:
////////////////////////////////////////////////////////////
/// \brief Get the sound buffer containing the captured audio data
///
/// The sound buffer is valid only after the capture has ended.
/// This function provides a read-only access to the internal
/// sound buffer, but it can be copied if you need to
/// make any modification to it.
///
/// \return Read-only access to the sound buffer
///
////////////////////////////////////////////////////////////
const SoundBuffer& getBuffer() const;
protected:
////////////////////////////////////////////////////////////
/// \brief Start capturing audio data
///
/// \return True to start the capture, or false to abort it
///
////////////////////////////////////////////////////////////
virtual bool onStart();
////////////////////////////////////////////////////////////
/// \brief Process a new chunk of recorded samples
///
/// \param samples Pointer to the new chunk of recorded samples
/// \param sampleCount Number of samples pointed by \a samples
///
/// \return True to continue the capture, or false to stop it
///
////////////////////////////////////////////////////////////
virtual bool onProcessSamples(const Int16* samples, std::size_t sampleCount);
////////////////////////////////////////////////////////////
/// \brief Stop capturing audio data
///
////////////////////////////////////////////////////////////
virtual void onStop();
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
std::vector<Int16> m_samples; ///< Temporary sample buffer to hold the recorded data
SoundBuffer m_buffer; ///< Sound buffer that will contain the recorded data
};
} // namespace sf
#endif // SFML_SOUNDBUFFERRECORDER_HPP
////////////////////////////////////////////////////////////
/// \class sf::SoundBufferRecorder
/// \ingroup audio
///
/// sf::SoundBufferRecorder allows to access a recorded sound
/// through a sf::SoundBuffer, so that it can be played, saved
/// to a file, etc.
///
/// It has the same simple interface as its base class (start(), stop())
/// and adds a function to retrieve the recorded sound buffer
/// (getBuffer()).
///
/// As usual, don't forget to call the isAvailable() function
/// before using this class (see sf::SoundRecorder for more details
/// about this).
///
/// Usage example:
/// \code
/// if (sf::SoundBufferRecorder::isAvailable())
/// {
/// // Record some audio data
/// sf::SoundBufferRecorder recorder;
/// recorder.start();
/// ...
/// recorder.stop();
///
/// // Get the buffer containing the captured audio data
/// const sf::SoundBuffer& buffer = recorder.getBuffer();
///
/// // Save it to a file (for example...)
/// buffer.saveToFile("my_record.ogg");
/// }
/// \endcode
///
/// \see sf::SoundRecorder
///
////////////////////////////////////////////////////////////

View file

@ -1,363 +1,363 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUNDRECORDER_HPP
#define SFML_SOUNDRECORDER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/System/Thread.hpp>
#include <SFML/System/Time.hpp>
#include <vector>
#include <string>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Abstract base class for capturing sound data
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API SoundRecorder
{
public :
////////////////////////////////////////////////////////////
/// \brief destructor
///
////////////////////////////////////////////////////////////
virtual ~SoundRecorder();
////////////////////////////////////////////////////////////
/// \brief Start the capture
///
/// The \a sampleRate parameter defines the number of audio samples
/// captured per second. The higher, the better the quality
/// (for example, 44100 samples/sec is CD quality).
/// This function uses its own thread so that it doesn't block
/// the rest of the program while the capture runs.
/// Please note that only one capture can happen at the same time.
/// You can select which capture device will be used, by passing
/// the name to the setDevice() method. If none was selected
/// before, the default capture device will be used. You can get a
/// list of the names of all available capture devices by calling
/// getAvailableDevices().
///
/// \param sampleRate Desired capture rate, in number of samples per second
///
/// \return True, if start of capture was successful
///
/// \see stop, getAvailableDevices
///
////////////////////////////////////////////////////////////
bool start(unsigned int sampleRate = 44100);
////////////////////////////////////////////////////////////
/// \brief Stop the capture
///
/// \see start
///
////////////////////////////////////////////////////////////
void stop();
////////////////////////////////////////////////////////////
/// \brief Get the sample rate
///
/// The sample rate defines the number of audio samples
/// captured per second. The higher, the better the quality
/// (for example, 44100 samples/sec is CD quality).
///
/// \return Sample rate, in samples per second
///
////////////////////////////////////////////////////////////
unsigned int getSampleRate() const;
////////////////////////////////////////////////////////////
/// \brief Get a list of the names of all availabe audio capture devices
///
/// This function returns a vector of strings, containing
/// the names of all availabe audio capture devices.
///
/// \return A vector of strings containing the names
///
////////////////////////////////////////////////////////////
static std::vector<std::string> getAvailableDevices();
////////////////////////////////////////////////////////////
/// \brief Get the name of the default audio capture device
///
/// This function returns the name of the default audio
/// capture device. If none is available, an empty string
/// is returned.
///
/// \return The name of the default audio capture device
///
////////////////////////////////////////////////////////////
static std::string getDefaultDevice();
////////////////////////////////////////////////////////////
/// \brief Set the audio capture device
///
/// This function sets the audio capture device to the device
/// with the given \a name. It can be called on the fly (i.e:
/// while recording). If you do so while recording and
/// opening the device fails, it stops the recording.
///
/// \param name The name of the audio capture device
///
/// \return True, if it was able to set the requested device
///
/// \see getAvailableDevices, getDefaultDevice
///
////////////////////////////////////////////////////////////
bool setDevice(const std::string& name);
////////////////////////////////////////////////////////////
/// \brief Get the name of the current audio capture device
///
/// \return The name of the current audio capture device
///
////////////////////////////////////////////////////////////
const std::string& getDevice() const;
////////////////////////////////////////////////////////////
/// \brief Check if the system supports audio capture
///
/// This function should always be called before using
/// the audio capture features. If it returns false, then
/// any attempt to use sf::SoundRecorder or one of its derived
/// classes will fail.
///
/// \return True if audio capture is supported, false otherwise
///
////////////////////////////////////////////////////////////
static bool isAvailable();
protected :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor is only meant to be called by derived classes.
///
////////////////////////////////////////////////////////////
SoundRecorder();
////////////////////////////////////////////////////////////
/// \brief Set the processing interval
///
/// The processing interval controls the period
/// between calls to the onProcessSamples function. You may
/// want to use a small interval if you want to process the
/// recorded data in real time, for example.
///
/// Note: this is only a hint, the actual period may vary.
/// So don't rely on this parameter to implement precise timing.
///
/// The default processing interval is 100 ms.
///
/// \param interval Processing interval
///
////////////////////////////////////////////////////////////
void setProcessingInterval(sf::Time interval);
////////////////////////////////////////////////////////////
/// \brief Start capturing audio data
///
/// This virtual function may be overriden by a derived class
/// if something has to be done every time a new capture
/// starts. If not, this function can be ignored; the default
/// implementation does nothing.
///
/// \return True to start the capture, or false to abort it
///
////////////////////////////////////////////////////////////
virtual bool onStart();
////////////////////////////////////////////////////////////
/// \brief Process a new chunk of recorded samples
///
/// This virtual function is called every time a new chunk of
/// recorded data is available. The derived class can then do
/// whatever it wants with it (storing it, playing it, sending
/// it over the network, etc.).
///
/// \param samples Pointer to the new chunk of recorded samples
/// \param sampleCount Number of samples pointed by \a samples
///
/// \return True to continue the capture, or false to stop it
///
////////////////////////////////////////////////////////////
virtual bool onProcessSamples(const Int16* samples, std::size_t sampleCount) = 0;
////////////////////////////////////////////////////////////
/// \brief Stop capturing audio data
///
/// This virtual function may be overriden by a derived class
/// if something has to be done every time the capture
/// ends. If not, this function can be ignored; the default
/// implementation does nothing.
///
////////////////////////////////////////////////////////////
virtual void onStop();
private :
////////////////////////////////////////////////////////////
/// \brief Function called as the entry point of the thread
///
/// This function starts the recording loop, and returns
/// only when the capture is stopped.
///
////////////////////////////////////////////////////////////
void record();
////////////////////////////////////////////////////////////
/// \brief Get the new available audio samples and process them
///
/// This function is called continuously during the
/// capture loop. It retrieves the captured samples and
/// forwards them to the derived class.
///
////////////////////////////////////////////////////////////
void processCapturedSamples();
////////////////////////////////////////////////////////////
/// \brief Clean up the recorder's internal resources
///
/// This function is called when the capture stops.
///
////////////////////////////////////////////////////////////
void cleanup();
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Thread m_thread; ///< Thread running the background recording task
std::vector<Int16> m_samples; ///< Buffer to store captured samples
unsigned int m_sampleRate; ///< Sample rate
sf::Time m_processingInterval; ///< Time period between calls to onProcessSamples
bool m_isCapturing; ///< Capturing state
std::string m_deviceName; ///< Name of the audio capture device
};
} // namespace sf
#endif // SFML_SOUNDRECORDER_HPP
////////////////////////////////////////////////////////////
/// \class sf::SoundRecorder
/// \ingroup audio
///
/// sf::SoundBuffer provides a simple interface to access
/// the audio recording capabilities of the computer
/// (the microphone). As an abstract base class, it only cares
/// about capturing sound samples, the task of making something
/// useful with them is left to the derived class. Note that
/// SFML provides a built-in specialization for saving the
/// captured data to a sound buffer (see sf::SoundBufferRecorder).
///
/// A derived class has only one virtual function to override:
/// \li onProcessSamples provides the new chunks of audio samples while the capture happens
///
/// Moreover, two additionnal virtual functions can be overriden
/// as well if necessary:
/// \li onStart is called before the capture happens, to perform custom initializations
/// \li onStop is called after the capture ends, to perform custom cleanup
///
/// A derived class can also control the frequency of the onProcessSamples
/// calls, with the setProcessingInterval protected function. The default
/// interval is chosen so that recording thread doesn't consume too much
/// CPU, but it can be changed to a smaller value if you need to process
/// the recorded data in real time, for example.
///
/// The audio capture feature may not be supported or activated
/// on every platform, thus it is recommended to check its
/// availability with the isAvailable() function. If it returns
/// false, then any attempt to use an audio recorder will fail.
///
/// If you have multiple sound input devices connected to your
/// computer (for example: microphone, external soundcard, webcam mic, ...)
/// you can get a list of all available devices throught the
/// getAvailableDevices() function. You can then select a device
/// by calling setDevice() with the appropiate device. Otherwise
/// the default capturing device will be used.
///
/// It is important to note that the audio capture happens in a
/// separate thread, so that it doesn't block the rest of the
/// program. In particular, the onProcessSamples virtual function
/// (but not onStart and not onStop) will be called
/// from this separate thread. It is important to keep this in
/// mind, because you may have to take care of synchronization
/// issues if you share data between threads.
///
/// Usage example:
/// \code
/// class CustomRecorder : public sf::SoundRecorder
/// {
/// virtual bool onStart() // optional
/// {
/// // Initialize whatever has to be done before the capture starts
/// ...
///
/// // Return true to start playing
/// return true;
/// }
///
/// virtual bool onProcessSamples(const Int16* samples, std::size_t sampleCount)
/// {
/// // Do something with the new chunk of samples (store them, send them, ...)
/// ...
///
/// // Return true to continue playing
/// return true;
/// }
///
/// virtual void onStop() // optional
/// {
/// // Clean up whatever has to be done after the capture ends
/// ...
/// }
/// }
///
/// // Usage
/// if (CustomRecorder::isAvailable())
/// {
/// CustomRecorder recorder;
///
/// if (!recorder.start())
/// return -1;
///
/// ...
/// recorder.stop();
/// }
/// \endcode
///
/// \see sf::SoundBufferRecorder
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUNDRECORDER_HPP
#define SFML_SOUNDRECORDER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/System/Thread.hpp>
#include <SFML/System/Time.hpp>
#include <vector>
#include <string>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Abstract base class for capturing sound data
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API SoundRecorder
{
public:
////////////////////////////////////////////////////////////
/// \brief destructor
///
////////////////////////////////////////////////////////////
virtual ~SoundRecorder();
////////////////////////////////////////////////////////////
/// \brief Start the capture
///
/// The \a sampleRate parameter defines the number of audio samples
/// captured per second. The higher, the better the quality
/// (for example, 44100 samples/sec is CD quality).
/// This function uses its own thread so that it doesn't block
/// the rest of the program while the capture runs.
/// Please note that only one capture can happen at the same time.
/// You can select which capture device will be used, by passing
/// the name to the setDevice() method. If none was selected
/// before, the default capture device will be used. You can get a
/// list of the names of all available capture devices by calling
/// getAvailableDevices().
///
/// \param sampleRate Desired capture rate, in number of samples per second
///
/// \return True, if start of capture was successful
///
/// \see stop, getAvailableDevices
///
////////////////////////////////////////////////////////////
bool start(unsigned int sampleRate = 44100);
////////////////////////////////////////////////////////////
/// \brief Stop the capture
///
/// \see start
///
////////////////////////////////////////////////////////////
void stop();
////////////////////////////////////////////////////////////
/// \brief Get the sample rate
///
/// The sample rate defines the number of audio samples
/// captured per second. The higher, the better the quality
/// (for example, 44100 samples/sec is CD quality).
///
/// \return Sample rate, in samples per second
///
////////////////////////////////////////////////////////////
unsigned int getSampleRate() const;
////////////////////////////////////////////////////////////
/// \brief Get a list of the names of all availabe audio capture devices
///
/// This function returns a vector of strings, containing
/// the names of all availabe audio capture devices.
///
/// \return A vector of strings containing the names
///
////////////////////////////////////////////////////////////
static std::vector<std::string> getAvailableDevices();
////////////////////////////////////////////////////////////
/// \brief Get the name of the default audio capture device
///
/// This function returns the name of the default audio
/// capture device. If none is available, an empty string
/// is returned.
///
/// \return The name of the default audio capture device
///
////////////////////////////////////////////////////////////
static std::string getDefaultDevice();
////////////////////////////////////////////////////////////
/// \brief Set the audio capture device
///
/// This function sets the audio capture device to the device
/// with the given \a name. It can be called on the fly (i.e:
/// while recording). If you do so while recording and
/// opening the device fails, it stops the recording.
///
/// \param name The name of the audio capture device
///
/// \return True, if it was able to set the requested device
///
/// \see getAvailableDevices, getDefaultDevice
///
////////////////////////////////////////////////////////////
bool setDevice(const std::string& name);
////////////////////////////////////////////////////////////
/// \brief Get the name of the current audio capture device
///
/// \return The name of the current audio capture device
///
////////////////////////////////////////////////////////////
const std::string& getDevice() const;
////////////////////////////////////////////////////////////
/// \brief Check if the system supports audio capture
///
/// This function should always be called before using
/// the audio capture features. If it returns false, then
/// any attempt to use sf::SoundRecorder or one of its derived
/// classes will fail.
///
/// \return True if audio capture is supported, false otherwise
///
////////////////////////////////////////////////////////////
static bool isAvailable();
protected:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor is only meant to be called by derived classes.
///
////////////////////////////////////////////////////////////
SoundRecorder();
////////////////////////////////////////////////////////////
/// \brief Set the processing interval
///
/// The processing interval controls the period
/// between calls to the onProcessSamples function. You may
/// want to use a small interval if you want to process the
/// recorded data in real time, for example.
///
/// Note: this is only a hint, the actual period may vary.
/// So don't rely on this parameter to implement precise timing.
///
/// The default processing interval is 100 ms.
///
/// \param interval Processing interval
///
////////////////////////////////////////////////////////////
void setProcessingInterval(sf::Time interval);
////////////////////////////////////////////////////////////
/// \brief Start capturing audio data
///
/// This virtual function may be overriden by a derived class
/// if something has to be done every time a new capture
/// starts. If not, this function can be ignored; the default
/// implementation does nothing.
///
/// \return True to start the capture, or false to abort it
///
////////////////////////////////////////////////////////////
virtual bool onStart();
////////////////////////////////////////////////////////////
/// \brief Process a new chunk of recorded samples
///
/// This virtual function is called every time a new chunk of
/// recorded data is available. The derived class can then do
/// whatever it wants with it (storing it, playing it, sending
/// it over the network, etc.).
///
/// \param samples Pointer to the new chunk of recorded samples
/// \param sampleCount Number of samples pointed by \a samples
///
/// \return True to continue the capture, or false to stop it
///
////////////////////////////////////////////////////////////
virtual bool onProcessSamples(const Int16* samples, std::size_t sampleCount) = 0;
////////////////////////////////////////////////////////////
/// \brief Stop capturing audio data
///
/// This virtual function may be overriden by a derived class
/// if something has to be done every time the capture
/// ends. If not, this function can be ignored; the default
/// implementation does nothing.
///
////////////////////////////////////////////////////////////
virtual void onStop();
private:
////////////////////////////////////////////////////////////
/// \brief Function called as the entry point of the thread
///
/// This function starts the recording loop, and returns
/// only when the capture is stopped.
///
////////////////////////////////////////////////////////////
void record();
////////////////////////////////////////////////////////////
/// \brief Get the new available audio samples and process them
///
/// This function is called continuously during the
/// capture loop. It retrieves the captured samples and
/// forwards them to the derived class.
///
////////////////////////////////////////////////////////////
void processCapturedSamples();
////////////////////////////////////////////////////////////
/// \brief Clean up the recorder's internal resources
///
/// This function is called when the capture stops.
///
////////////////////////////////////////////////////////////
void cleanup();
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Thread m_thread; ///< Thread running the background recording task
std::vector<Int16> m_samples; ///< Buffer to store captured samples
unsigned int m_sampleRate; ///< Sample rate
sf::Time m_processingInterval; ///< Time period between calls to onProcessSamples
bool m_isCapturing; ///< Capturing state
std::string m_deviceName; ///< Name of the audio capture device
};
} // namespace sf
#endif // SFML_SOUNDRECORDER_HPP
////////////////////////////////////////////////////////////
/// \class sf::SoundRecorder
/// \ingroup audio
///
/// sf::SoundBuffer provides a simple interface to access
/// the audio recording capabilities of the computer
/// (the microphone). As an abstract base class, it only cares
/// about capturing sound samples, the task of making something
/// useful with them is left to the derived class. Note that
/// SFML provides a built-in specialization for saving the
/// captured data to a sound buffer (see sf::SoundBufferRecorder).
///
/// A derived class has only one virtual function to override:
/// \li onProcessSamples provides the new chunks of audio samples while the capture happens
///
/// Moreover, two additionnal virtual functions can be overriden
/// as well if necessary:
/// \li onStart is called before the capture happens, to perform custom initializations
/// \li onStop is called after the capture ends, to perform custom cleanup
///
/// A derived class can also control the frequency of the onProcessSamples
/// calls, with the setProcessingInterval protected function. The default
/// interval is chosen so that recording thread doesn't consume too much
/// CPU, but it can be changed to a smaller value if you need to process
/// the recorded data in real time, for example.
///
/// The audio capture feature may not be supported or activated
/// on every platform, thus it is recommended to check its
/// availability with the isAvailable() function. If it returns
/// false, then any attempt to use an audio recorder will fail.
///
/// If you have multiple sound input devices connected to your
/// computer (for example: microphone, external soundcard, webcam mic, ...)
/// you can get a list of all available devices throught the
/// getAvailableDevices() function. You can then select a device
/// by calling setDevice() with the appropiate device. Otherwise
/// the default capturing device will be used.
///
/// It is important to note that the audio capture happens in a
/// separate thread, so that it doesn't block the rest of the
/// program. In particular, the onProcessSamples virtual function
/// (but not onStart and not onStop) will be called
/// from this separate thread. It is important to keep this in
/// mind, because you may have to take care of synchronization
/// issues if you share data between threads.
///
/// Usage example:
/// \code
/// class CustomRecorder : public sf::SoundRecorder
/// {
/// virtual bool onStart() // optional
/// {
/// // Initialize whatever has to be done before the capture starts
/// ...
///
/// // Return true to start playing
/// return true;
/// }
///
/// virtual bool onProcessSamples(const Int16* samples, std::size_t sampleCount)
/// {
/// // Do something with the new chunk of samples (store them, send them, ...)
/// ...
///
/// // Return true to continue playing
/// return true;
/// }
///
/// virtual void onStop() // optional
/// {
/// // Clean up whatever has to be done after the capture ends
/// ...
/// }
/// }
///
/// // Usage
/// if (CustomRecorder::isAvailable())
/// {
/// CustomRecorder recorder;
///
/// if (!recorder.start())
/// return -1;
///
/// ...
/// recorder.stop();
/// }
/// \endcode
///
/// \see sf::SoundBufferRecorder
///
////////////////////////////////////////////////////////////

View file

@ -1,286 +1,286 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUNDSOURCE_HPP
#define SFML_SOUNDSOURCE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/System/Vector3.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Base class defining a sound's properties
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API SoundSource
{
public :
////////////////////////////////////////////////////////////
/// \brief Enumeration of the sound source states
///
////////////////////////////////////////////////////////////
enum Status
{
Stopped, ///< Sound is not playing
Paused, ///< Sound is paused
Playing ///< Sound is playing
};
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
SoundSource(const SoundSource& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~SoundSource();
////////////////////////////////////////////////////////////
/// \brief Set the pitch of the sound
///
/// The pitch represents the perceived fundamental frequency
/// of a sound; thus you can make a sound more acute or grave
/// by changing its pitch. A side effect of changing the pitch
/// is to modify the playing speed of the sound as well.
/// The default value for the pitch is 1.
///
/// \param pitch New pitch to apply to the sound
///
/// \see getPitch
///
////////////////////////////////////////////////////////////
void setPitch(float pitch);
////////////////////////////////////////////////////////////
/// \brief Set the volume of the sound
///
/// The volume is a value between 0 (mute) and 100 (full volume).
/// The default value for the volume is 100.
///
/// \param volume Volume of the sound
///
/// \see getVolume
///
////////////////////////////////////////////////////////////
void setVolume(float volume);
////////////////////////////////////////////////////////////
/// \brief Set the 3D position of the sound in the audio scene
///
/// Only sounds with one channel (mono sounds) can be
/// spatialized.
/// The default position of a sound is (0, 0, 0).
///
/// \param x X coordinate of the position of the sound in the scene
/// \param y Y coordinate of the position of the sound in the scene
/// \param z Z coordinate of the position of the sound in the scene
///
/// \see getPosition
///
////////////////////////////////////////////////////////////
void setPosition(float x, float y, float z);
////////////////////////////////////////////////////////////
/// \brief Set the 3D position of the sound in the audio scene
///
/// Only sounds with one channel (mono sounds) can be
/// spatialized.
/// The default position of a sound is (0, 0, 0).
///
/// \param position Position of the sound in the scene
///
/// \see getPosition
///
////////////////////////////////////////////////////////////
void setPosition(const Vector3f& position);
////////////////////////////////////////////////////////////
/// \brief Make the sound's position relative to the listener or absolute
///
/// Making a sound relative to the listener will ensure that it will always
/// be played the same way regardless the position of the listener.
/// This can be useful for non-spatialized sounds, sounds that are
/// produced by the listener, or sounds attached to it.
/// The default value is false (position is absolute).
///
/// \param relative True to set the position relative, false to set it absolute
///
/// \see isRelativeToListener
///
////////////////////////////////////////////////////////////
void setRelativeToListener(bool relative);
////////////////////////////////////////////////////////////
/// \brief Set the minimum distance of the sound
///
/// The "minimum distance" of a sound is the maximum
/// distance at which it is heard at its maximum volume. Further
/// than the minimum distance, it will start to fade out according
/// to its attenuation factor. A value of 0 ("inside the head
/// of the listener") is an invalid value and is forbidden.
/// The default value of the minimum distance is 1.
///
/// \param distance New minimum distance of the sound
///
/// \see getMinDistance, setAttenuation
///
////////////////////////////////////////////////////////////
void setMinDistance(float distance);
////////////////////////////////////////////////////////////
/// \brief Set the attenuation factor of the sound
///
/// The attenuation is a multiplicative factor which makes
/// the sound more or less loud according to its distance
/// from the listener. An attenuation of 0 will produce a
/// non-attenuated sound, i.e. its volume will always be the same
/// whether it is heard from near or from far. On the other hand,
/// an attenuation value such as 100 will make the sound fade out
/// very quickly as it gets further from the listener.
/// The default value of the attenuation is 1.
///
/// \param attenuation New attenuation factor of the sound
///
/// \see getAttenuation, setMinDistance
///
////////////////////////////////////////////////////////////
void setAttenuation(float attenuation);
////////////////////////////////////////////////////////////
/// \brief Get the pitch of the sound
///
/// \return Pitch of the sound
///
/// \see setPitch
///
////////////////////////////////////////////////////////////
float getPitch() const;
////////////////////////////////////////////////////////////
/// \brief Get the volume of the sound
///
/// \return Volume of the sound, in the range [0, 100]
///
/// \see setVolume
///
////////////////////////////////////////////////////////////
float getVolume() const;
////////////////////////////////////////////////////////////
/// \brief Get the 3D position of the sound in the audio scene
///
/// \return Position of the sound
///
/// \see setPosition
///
////////////////////////////////////////////////////////////
Vector3f getPosition() const;
////////////////////////////////////////////////////////////
/// \brief Tell whether the sound's position is relative to the
/// listener or is absolute
///
/// \return True if the position is relative, false if it's absolute
///
/// \see setRelativeToListener
///
////////////////////////////////////////////////////////////
bool isRelativeToListener() const;
////////////////////////////////////////////////////////////
/// \brief Get the minimum distance of the sound
///
/// \return Minimum distance of the sound
///
/// \see setMinDistance, getAttenuation
///
////////////////////////////////////////////////////////////
float getMinDistance() const;
////////////////////////////////////////////////////////////
/// \brief Get the attenuation factor of the sound
///
/// \return Attenuation factor of the sound
///
/// \see setAttenuation, getMinDistance
///
////////////////////////////////////////////////////////////
float getAttenuation() const;
protected :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor is meant ot be called by derived classes only.
///
////////////////////////////////////////////////////////////
SoundSource();
////////////////////////////////////////////////////////////
/// \brief Get the current status of the sound (stopped, paused, playing)
///
/// \return Current status of the sound
///
////////////////////////////////////////////////////////////
Status getStatus() const;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
unsigned int m_source; ///< OpenAL source identifier
};
} // namespace sf
#endif // SFML_SOUNDSOURCE_HPP
////////////////////////////////////////////////////////////
/// \class sf::SoundSource
/// \ingroup audio
///
/// sf::SoundSource is not meant to be used directly, it
/// only serves as a common base for all audio objects
/// that can live in the audio environment.
///
/// It defines several properties for the sound: pitch,
/// volume, position, attenuation, etc. All of them can be
/// changed at any time with no impact on performances.
///
/// \see sf::Sound, sf::SoundStream
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUNDSOURCE_HPP
#define SFML_SOUNDSOURCE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/System/Vector3.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Base class defining a sound's properties
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API SoundSource
{
public:
////////////////////////////////////////////////////////////
/// \brief Enumeration of the sound source states
///
////////////////////////////////////////////////////////////
enum Status
{
Stopped, ///< Sound is not playing
Paused, ///< Sound is paused
Playing ///< Sound is playing
};
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
SoundSource(const SoundSource& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~SoundSource();
////////////////////////////////////////////////////////////
/// \brief Set the pitch of the sound
///
/// The pitch represents the perceived fundamental frequency
/// of a sound; thus you can make a sound more acute or grave
/// by changing its pitch. A side effect of changing the pitch
/// is to modify the playing speed of the sound as well.
/// The default value for the pitch is 1.
///
/// \param pitch New pitch to apply to the sound
///
/// \see getPitch
///
////////////////////////////////////////////////////////////
void setPitch(float pitch);
////////////////////////////////////////////////////////////
/// \brief Set the volume of the sound
///
/// The volume is a value between 0 (mute) and 100 (full volume).
/// The default value for the volume is 100.
///
/// \param volume Volume of the sound
///
/// \see getVolume
///
////////////////////////////////////////////////////////////
void setVolume(float volume);
////////////////////////////////////////////////////////////
/// \brief Set the 3D position of the sound in the audio scene
///
/// Only sounds with one channel (mono sounds) can be
/// spatialized.
/// The default position of a sound is (0, 0, 0).
///
/// \param x X coordinate of the position of the sound in the scene
/// \param y Y coordinate of the position of the sound in the scene
/// \param z Z coordinate of the position of the sound in the scene
///
/// \see getPosition
///
////////////////////////////////////////////////////////////
void setPosition(float x, float y, float z);
////////////////////////////////////////////////////////////
/// \brief Set the 3D position of the sound in the audio scene
///
/// Only sounds with one channel (mono sounds) can be
/// spatialized.
/// The default position of a sound is (0, 0, 0).
///
/// \param position Position of the sound in the scene
///
/// \see getPosition
///
////////////////////////////////////////////////////////////
void setPosition(const Vector3f& position);
////////////////////////////////////////////////////////////
/// \brief Make the sound's position relative to the listener or absolute
///
/// Making a sound relative to the listener will ensure that it will always
/// be played the same way regardless the position of the listener.
/// This can be useful for non-spatialized sounds, sounds that are
/// produced by the listener, or sounds attached to it.
/// The default value is false (position is absolute).
///
/// \param relative True to set the position relative, false to set it absolute
///
/// \see isRelativeToListener
///
////////////////////////////////////////////////////////////
void setRelativeToListener(bool relative);
////////////////////////////////////////////////////////////
/// \brief Set the minimum distance of the sound
///
/// The "minimum distance" of a sound is the maximum
/// distance at which it is heard at its maximum volume. Further
/// than the minimum distance, it will start to fade out according
/// to its attenuation factor. A value of 0 ("inside the head
/// of the listener") is an invalid value and is forbidden.
/// The default value of the minimum distance is 1.
///
/// \param distance New minimum distance of the sound
///
/// \see getMinDistance, setAttenuation
///
////////////////////////////////////////////////////////////
void setMinDistance(float distance);
////////////////////////////////////////////////////////////
/// \brief Set the attenuation factor of the sound
///
/// The attenuation is a multiplicative factor which makes
/// the sound more or less loud according to its distance
/// from the listener. An attenuation of 0 will produce a
/// non-attenuated sound, i.e. its volume will always be the same
/// whether it is heard from near or from far. On the other hand,
/// an attenuation value such as 100 will make the sound fade out
/// very quickly as it gets further from the listener.
/// The default value of the attenuation is 1.
///
/// \param attenuation New attenuation factor of the sound
///
/// \see getAttenuation, setMinDistance
///
////////////////////////////////////////////////////////////
void setAttenuation(float attenuation);
////////////////////////////////////////////////////////////
/// \brief Get the pitch of the sound
///
/// \return Pitch of the sound
///
/// \see setPitch
///
////////////////////////////////////////////////////////////
float getPitch() const;
////////////////////////////////////////////////////////////
/// \brief Get the volume of the sound
///
/// \return Volume of the sound, in the range [0, 100]
///
/// \see setVolume
///
////////////////////////////////////////////////////////////
float getVolume() const;
////////////////////////////////////////////////////////////
/// \brief Get the 3D position of the sound in the audio scene
///
/// \return Position of the sound
///
/// \see setPosition
///
////////////////////////////////////////////////////////////
Vector3f getPosition() const;
////////////////////////////////////////////////////////////
/// \brief Tell whether the sound's position is relative to the
/// listener or is absolute
///
/// \return True if the position is relative, false if it's absolute
///
/// \see setRelativeToListener
///
////////////////////////////////////////////////////////////
bool isRelativeToListener() const;
////////////////////////////////////////////////////////////
/// \brief Get the minimum distance of the sound
///
/// \return Minimum distance of the sound
///
/// \see setMinDistance, getAttenuation
///
////////////////////////////////////////////////////////////
float getMinDistance() const;
////////////////////////////////////////////////////////////
/// \brief Get the attenuation factor of the sound
///
/// \return Attenuation factor of the sound
///
/// \see setAttenuation, getMinDistance
///
////////////////////////////////////////////////////////////
float getAttenuation() const;
protected:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor is meant ot be called by derived classes only.
///
////////////////////////////////////////////////////////////
SoundSource();
////////////////////////////////////////////////////////////
/// \brief Get the current status of the sound (stopped, paused, playing)
///
/// \return Current status of the sound
///
////////////////////////////////////////////////////////////
Status getStatus() const;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
unsigned int m_source; ///< OpenAL source identifier
};
} // namespace sf
#endif // SFML_SOUNDSOURCE_HPP
////////////////////////////////////////////////////////////
/// \class sf::SoundSource
/// \ingroup audio
///
/// sf::SoundSource is not meant to be used directly, it
/// only serves as a common base for all audio objects
/// that can live in the audio environment.
///
/// It defines several properties for the sound: pitch,
/// volume, position, attenuation, etc. All of them can be
/// changed at any time with no impact on performances.
///
/// \see sf::Sound, sf::SoundStream
///
////////////////////////////////////////////////////////////

View file

@ -1,386 +1,386 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUNDSTREAM_HPP
#define SFML_SOUNDSTREAM_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/Audio/SoundSource.hpp>
#include <SFML/System/Thread.hpp>
#include <SFML/System/Time.hpp>
#include <SFML/System/Mutex.hpp>
#include <cstdlib>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Abstract base class for streamed audio sources
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API SoundStream : public SoundSource
{
public :
////////////////////////////////////////////////////////////
/// \brief Structure defining a chunk of audio data to stream
///
////////////////////////////////////////////////////////////
struct Chunk
{
const Int16* samples; ///< Pointer to the audio samples
std::size_t sampleCount; ///< Number of samples pointed by Samples
};
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~SoundStream();
////////////////////////////////////////////////////////////
/// \brief Start or resume playing the audio stream
///
/// This function starts the stream if it was stopped, resumes
/// it if it was paused, and restarts it from the beginning if
/// it was already playing.
/// This function uses its own thread so that it doesn't block
/// the rest of the program while the stream is played.
///
/// \see pause, stop
///
////////////////////////////////////////////////////////////
void play();
////////////////////////////////////////////////////////////
/// \brief Pause the audio stream
///
/// This function pauses the stream if it was playing,
/// otherwise (stream already paused or stopped) it has no effect.
///
/// \see play, stop
///
////////////////////////////////////////////////////////////
void pause();
////////////////////////////////////////////////////////////
/// \brief Stop playing the audio stream
///
/// This function stops the stream if it was playing or paused,
/// and does nothing if it was already stopped.
/// It also resets the playing position (unlike pause()).
///
/// \see play, pause
///
////////////////////////////////////////////////////////////
void stop();
////////////////////////////////////////////////////////////
/// \brief Return the number of channels of the stream
///
/// 1 channel means a mono sound, 2 means stereo, etc.
///
/// \return Number of channels
///
////////////////////////////////////////////////////////////
unsigned int getChannelCount() const;
////////////////////////////////////////////////////////////
/// \brief Get the stream sample rate of the stream
///
/// The sample rate is the number of audio samples played per
/// second. The higher, the better the quality.
///
/// \return Sample rate, in number of samples per second
///
////////////////////////////////////////////////////////////
unsigned int getSampleRate() const;
////////////////////////////////////////////////////////////
/// \brief Get the current status of the stream (stopped, paused, playing)
///
/// \return Current status
///
////////////////////////////////////////////////////////////
Status getStatus() const;
////////////////////////////////////////////////////////////
/// \brief Change the current playing position of the stream
///
/// The playing position can be changed when the stream is
/// either paused or playing. Changing the playing position
/// when the stream is stopped has no effect, since playing
/// the stream would reset its position.
///
/// \param timeOffset New playing position, from the beginning of the stream
///
/// \see getPlayingOffset
///
////////////////////////////////////////////////////////////
void setPlayingOffset(Time timeOffset);
////////////////////////////////////////////////////////////
/// \brief Get the current playing position of the stream
///
/// \return Current playing position, from the beginning of the stream
///
/// \see setPlayingOffset
///
////////////////////////////////////////////////////////////
Time getPlayingOffset() const;
////////////////////////////////////////////////////////////
/// \brief Set whether or not the stream should loop after reaching the end
///
/// If set, the stream will restart from beginning after
/// reaching the end and so on, until it is stopped or
/// setLoop(false) is called.
/// The default looping state for streams is false.
///
/// \param loop True to play in loop, false to play once
///
/// \see getLoop
///
////////////////////////////////////////////////////////////
void setLoop(bool loop);
////////////////////////////////////////////////////////////
/// \brief Tell whether or not the stream is in loop mode
///
/// \return True if the stream is looping, false otherwise
///
/// \see setLoop
///
////////////////////////////////////////////////////////////
bool getLoop() const;
protected :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor is only meant to be called by derived classes.
///
////////////////////////////////////////////////////////////
SoundStream();
////////////////////////////////////////////////////////////
/// \brief Define the audio stream parameters
///
/// This function must be called by derived classes as soon
/// as they know the audio settings of the stream to play.
/// Any attempt to manipulate the stream (play(), ...) before
/// calling this function will fail.
/// It can be called multiple times if the settings of the
/// audio stream change, but only when the stream is stopped.
///
/// \param channelCount Number of channels of the stream
/// \param sampleRate Sample rate, in samples per second
///
////////////////////////////////////////////////////////////
void initialize(unsigned int channelCount, unsigned int sampleRate);
////////////////////////////////////////////////////////////
/// \brief Request a new chunk of audio samples from the stream source
///
/// This function must be overriden by derived classes to provide
/// the audio samples to play. It is called continuously by the
/// streaming loop, in a separate thread.
/// The source can choose to stop the streaming loop at any time, by
/// returning false to the caller.
/// If you return true (i.e. continue streaming) it is important that
/// the returned array of samples is not empty; this would stop the stream
/// due to an internal limitation.
///
/// \param data Chunk of data to fill
///
/// \return True to continue playback, false to stop
///
////////////////////////////////////////////////////////////
virtual bool onGetData(Chunk& data) = 0;
////////////////////////////////////////////////////////////
/// \brief Change the current playing position in the stream source
///
/// This function must be overriden by derived classes to
/// allow random seeking into the stream source.
///
/// \param timeOffset New playing position, relative to the beginning of the stream
///
////////////////////////////////////////////////////////////
virtual void onSeek(Time timeOffset) = 0;
private :
////////////////////////////////////////////////////////////
/// \brief Function called as the entry point of the thread
///
/// This function starts the streaming loop, and returns
/// only when the sound is stopped.
///
////////////////////////////////////////////////////////////
void streamData();
////////////////////////////////////////////////////////////
/// \brief Fill a new buffer with audio samples, and append
/// it to the playing queue
///
/// This function is called as soon as a buffer has been fully
/// consumed; it fills it again and inserts it back into the
/// playing queue.
///
/// \param bufferNum Number of the buffer to fill (in [0, BufferCount])
///
/// \return True if the stream source has requested to stop, false otherwise
///
////////////////////////////////////////////////////////////
bool fillAndPushBuffer(unsigned int bufferNum);
////////////////////////////////////////////////////////////
/// \brief Fill the audio buffers and put them all into the playing queue
///
/// This function is called when playing starts and the
/// playing queue is empty.
///
/// \return True if the derived class has requested to stop, false otherwise
///
////////////////////////////////////////////////////////////
bool fillQueue();
////////////////////////////////////////////////////////////
/// \brief Clear all the audio buffers and empty the playing queue
///
/// This function is called when the stream is stopped.
///
////////////////////////////////////////////////////////////
void clearQueue();
enum
{
BufferCount = 3 ///< Number of audio buffers used by the streaming loop
};
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Thread m_thread; ///< Thread running the background tasks
mutable Mutex m_threadMutex; ///< Thread mutex
Status m_threadStartState; ///< State the thread starts in (Playing, Paused, Stopped)
bool m_isStreaming; ///< Streaming state (true = playing, false = stopped)
unsigned int m_buffers[BufferCount]; ///< Sound buffers used to store temporary audio data
unsigned int m_channelCount; ///< Number of channels (1 = mono, 2 = stereo, ...)
unsigned int m_sampleRate; ///< Frequency (samples / second)
Uint32 m_format; ///< Format of the internal sound buffers
bool m_loop; ///< Loop flag (true to loop, false to play once)
Uint64 m_samplesProcessed; ///< Number of buffers processed since beginning of the stream
bool m_endBuffers[BufferCount]; ///< Each buffer is marked as "end buffer" or not, for proper duration calculation
};
} // namespace sf
#endif // SFML_SOUNDSTREAM_HPP
////////////////////////////////////////////////////////////
/// \class sf::SoundStream
/// \ingroup audio
///
/// Unlike audio buffers (see sf::SoundBuffer), audio streams
/// are never completely loaded in memory. Instead, the audio
/// data is acquired continuously while the stream is playing.
/// This behaviour allows to play a sound with no loading delay,
/// and keeps the memory consumption very low.
///
/// Sound sources that need to be streamed are usually big files
/// (compressed audio musics that would eat hundreds of MB in memory)
/// or files that would take a lot of time to be received
/// (sounds played over the network).
///
/// sf::SoundStream is a base class that doesn't care about the
/// stream source, which is left to the derived class. SFML provides
/// a built-in specialization for big files (see sf::Music).
/// No network stream source is provided, but you can write your own
/// by combining this class with the network module.
///
/// A derived class has to override two virtual functions:
/// \li onGetData fills a new chunk of audio data to be played
/// \li onSeek changes the current playing position in the source
///
/// It is important to note that each SoundStream is played in its
/// own separate thread, so that the streaming loop doesn't block the
/// rest of the program. In particular, the OnGetData and OnSeek
/// virtual functions may sometimes be called from this separate thread.
/// It is important to keep this in mind, because you may have to take
/// care of synchronization issues if you share data between threads.
///
/// Usage example:
/// \code
/// class CustomStream : public sf::SoundStream
/// {
/// public :
///
/// bool open(const std::string& location)
/// {
/// // Open the source and get audio settings
/// ...
/// unsigned int channelCount = ...;
/// unsigned int sampleRate = ...;
///
/// // Initialize the stream -- important!
/// initialize(channelCount, sampleRate);
/// }
///
/// private :
///
/// virtual bool onGetData(Chunk& data)
/// {
/// // Fill the chunk with audio data from the stream source
/// // (note: must not be empty if you want to continue playing)
/// data.samples = ...;
/// data.sampleCount = ...;
///
/// // Return true to continue playing
/// return true;
/// }
///
/// virtual void onSeek(Uint32 timeOffset)
/// {
/// // Change the current position in the stream source
/// ...
/// }
/// }
///
/// // Usage
/// CustomStream stream;
/// stream.open("path/to/stream");
/// stream.play();
/// \endcode
///
/// \see sf::Music
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOUNDSTREAM_HPP
#define SFML_SOUNDSTREAM_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Export.hpp>
#include <SFML/Audio/SoundSource.hpp>
#include <SFML/System/Thread.hpp>
#include <SFML/System/Time.hpp>
#include <SFML/System/Mutex.hpp>
#include <cstdlib>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Abstract base class for streamed audio sources
///
////////////////////////////////////////////////////////////
class SFML_AUDIO_API SoundStream : public SoundSource
{
public:
////////////////////////////////////////////////////////////
/// \brief Structure defining a chunk of audio data to stream
///
////////////////////////////////////////////////////////////
struct Chunk
{
const Int16* samples; ///< Pointer to the audio samples
std::size_t sampleCount; ///< Number of samples pointed by Samples
};
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~SoundStream();
////////////////////////////////////////////////////////////
/// \brief Start or resume playing the audio stream
///
/// This function starts the stream if it was stopped, resumes
/// it if it was paused, and restarts it from the beginning if
/// it was already playing.
/// This function uses its own thread so that it doesn't block
/// the rest of the program while the stream is played.
///
/// \see pause, stop
///
////////////////////////////////////////////////////////////
void play();
////////////////////////////////////////////////////////////
/// \brief Pause the audio stream
///
/// This function pauses the stream if it was playing,
/// otherwise (stream already paused or stopped) it has no effect.
///
/// \see play, stop
///
////////////////////////////////////////////////////////////
void pause();
////////////////////////////////////////////////////////////
/// \brief Stop playing the audio stream
///
/// This function stops the stream if it was playing or paused,
/// and does nothing if it was already stopped.
/// It also resets the playing position (unlike pause()).
///
/// \see play, pause
///
////////////////////////////////////////////////////////////
void stop();
////////////////////////////////////////////////////////////
/// \brief Return the number of channels of the stream
///
/// 1 channel means a mono sound, 2 means stereo, etc.
///
/// \return Number of channels
///
////////////////////////////////////////////////////////////
unsigned int getChannelCount() const;
////////////////////////////////////////////////////////////
/// \brief Get the stream sample rate of the stream
///
/// The sample rate is the number of audio samples played per
/// second. The higher, the better the quality.
///
/// \return Sample rate, in number of samples per second
///
////////////////////////////////////////////////////////////
unsigned int getSampleRate() const;
////////////////////////////////////////////////////////////
/// \brief Get the current status of the stream (stopped, paused, playing)
///
/// \return Current status
///
////////////////////////////////////////////////////////////
Status getStatus() const;
////////////////////////////////////////////////////////////
/// \brief Change the current playing position of the stream
///
/// The playing position can be changed when the stream is
/// either paused or playing. Changing the playing position
/// when the stream is stopped has no effect, since playing
/// the stream would reset its position.
///
/// \param timeOffset New playing position, from the beginning of the stream
///
/// \see getPlayingOffset
///
////////////////////////////////////////////////////////////
void setPlayingOffset(Time timeOffset);
////////////////////////////////////////////////////////////
/// \brief Get the current playing position of the stream
///
/// \return Current playing position, from the beginning of the stream
///
/// \see setPlayingOffset
///
////////////////////////////////////////////////////////////
Time getPlayingOffset() const;
////////////////////////////////////////////////////////////
/// \brief Set whether or not the stream should loop after reaching the end
///
/// If set, the stream will restart from beginning after
/// reaching the end and so on, until it is stopped or
/// setLoop(false) is called.
/// The default looping state for streams is false.
///
/// \param loop True to play in loop, false to play once
///
/// \see getLoop
///
////////////////////////////////////////////////////////////
void setLoop(bool loop);
////////////////////////////////////////////////////////////
/// \brief Tell whether or not the stream is in loop mode
///
/// \return True if the stream is looping, false otherwise
///
/// \see setLoop
///
////////////////////////////////////////////////////////////
bool getLoop() const;
protected:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor is only meant to be called by derived classes.
///
////////////////////////////////////////////////////////////
SoundStream();
////////////////////////////////////////////////////////////
/// \brief Define the audio stream parameters
///
/// This function must be called by derived classes as soon
/// as they know the audio settings of the stream to play.
/// Any attempt to manipulate the stream (play(), ...) before
/// calling this function will fail.
/// It can be called multiple times if the settings of the
/// audio stream change, but only when the stream is stopped.
///
/// \param channelCount Number of channels of the stream
/// \param sampleRate Sample rate, in samples per second
///
////////////////////////////////////////////////////////////
void initialize(unsigned int channelCount, unsigned int sampleRate);
////////////////////////////////////////////////////////////
/// \brief Request a new chunk of audio samples from the stream source
///
/// This function must be overriden by derived classes to provide
/// the audio samples to play. It is called continuously by the
/// streaming loop, in a separate thread.
/// The source can choose to stop the streaming loop at any time, by
/// returning false to the caller.
/// If you return true (i.e. continue streaming) it is important that
/// the returned array of samples is not empty; this would stop the stream
/// due to an internal limitation.
///
/// \param data Chunk of data to fill
///
/// \return True to continue playback, false to stop
///
////////////////////////////////////////////////////////////
virtual bool onGetData(Chunk& data) = 0;
////////////////////////////////////////////////////////////
/// \brief Change the current playing position in the stream source
///
/// This function must be overriden by derived classes to
/// allow random seeking into the stream source.
///
/// \param timeOffset New playing position, relative to the beginning of the stream
///
////////////////////////////////////////////////////////////
virtual void onSeek(Time timeOffset) = 0;
private:
////////////////////////////////////////////////////////////
/// \brief Function called as the entry point of the thread
///
/// This function starts the streaming loop, and returns
/// only when the sound is stopped.
///
////////////////////////////////////////////////////////////
void streamData();
////////////////////////////////////////////////////////////
/// \brief Fill a new buffer with audio samples, and append
/// it to the playing queue
///
/// This function is called as soon as a buffer has been fully
/// consumed; it fills it again and inserts it back into the
/// playing queue.
///
/// \param bufferNum Number of the buffer to fill (in [0, BufferCount])
///
/// \return True if the stream source has requested to stop, false otherwise
///
////////////////////////////////////////////////////////////
bool fillAndPushBuffer(unsigned int bufferNum);
////////////////////////////////////////////////////////////
/// \brief Fill the audio buffers and put them all into the playing queue
///
/// This function is called when playing starts and the
/// playing queue is empty.
///
/// \return True if the derived class has requested to stop, false otherwise
///
////////////////////////////////////////////////////////////
bool fillQueue();
////////////////////////////////////////////////////////////
/// \brief Clear all the audio buffers and empty the playing queue
///
/// This function is called when the stream is stopped.
///
////////////////////////////////////////////////////////////
void clearQueue();
enum
{
BufferCount = 3 ///< Number of audio buffers used by the streaming loop
};
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Thread m_thread; ///< Thread running the background tasks
mutable Mutex m_threadMutex; ///< Thread mutex
Status m_threadStartState; ///< State the thread starts in (Playing, Paused, Stopped)
bool m_isStreaming; ///< Streaming state (true = playing, false = stopped)
unsigned int m_buffers[BufferCount]; ///< Sound buffers used to store temporary audio data
unsigned int m_channelCount; ///< Number of channels (1 = mono, 2 = stereo, ...)
unsigned int m_sampleRate; ///< Frequency (samples / second)
Uint32 m_format; ///< Format of the internal sound buffers
bool m_loop; ///< Loop flag (true to loop, false to play once)
Uint64 m_samplesProcessed; ///< Number of buffers processed since beginning of the stream
bool m_endBuffers[BufferCount]; ///< Each buffer is marked as "end buffer" or not, for proper duration calculation
};
} // namespace sf
#endif // SFML_SOUNDSTREAM_HPP
////////////////////////////////////////////////////////////
/// \class sf::SoundStream
/// \ingroup audio
///
/// Unlike audio buffers (see sf::SoundBuffer), audio streams
/// are never completely loaded in memory. Instead, the audio
/// data is acquired continuously while the stream is playing.
/// This behaviour allows to play a sound with no loading delay,
/// and keeps the memory consumption very low.
///
/// Sound sources that need to be streamed are usually big files
/// (compressed audio musics that would eat hundreds of MB in memory)
/// or files that would take a lot of time to be received
/// (sounds played over the network).
///
/// sf::SoundStream is a base class that doesn't care about the
/// stream source, which is left to the derived class. SFML provides
/// a built-in specialization for big files (see sf::Music).
/// No network stream source is provided, but you can write your own
/// by combining this class with the network module.
///
/// A derived class has to override two virtual functions:
/// \li onGetData fills a new chunk of audio data to be played
/// \li onSeek changes the current playing position in the source
///
/// It is important to note that each SoundStream is played in its
/// own separate thread, so that the streaming loop doesn't block the
/// rest of the program. In particular, the OnGetData and OnSeek
/// virtual functions may sometimes be called from this separate thread.
/// It is important to keep this in mind, because you may have to take
/// care of synchronization issues if you share data between threads.
///
/// Usage example:
/// \code
/// class CustomStream : public sf::SoundStream
/// {
/// public:
///
/// bool open(const std::string& location)
/// {
/// // Open the source and get audio settings
/// ...
/// unsigned int channelCount = ...;
/// unsigned int sampleRate = ...;
///
/// // Initialize the stream -- important!
/// initialize(channelCount, sampleRate);
/// }
///
/// private:
///
/// virtual bool onGetData(Chunk& data)
/// {
/// // Fill the chunk with audio data from the stream source
/// // (note: must not be empty if you want to continue playing)
/// data.samples = ...;
/// data.sampleCount = ...;
///
/// // Return true to continue playing
/// return true;
/// }
///
/// virtual void onSeek(Uint32 timeOffset)
/// {
/// // Change the current position in the stream source
/// ...
/// }
/// }
///
/// // Usage
/// CustomStream stream;
/// stream.open("path/to/stream");
/// stream.play();
/// \endcode
///
/// \see sf::Music
///
////////////////////////////////////////////////////////////

View file

@ -1,192 +1,192 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_CONFIG_HPP
#define SFML_CONFIG_HPP
////////////////////////////////////////////////////////////
// Define the SFML version
////////////////////////////////////////////////////////////
#define SFML_VERSION_MAJOR 2
#define SFML_VERSION_MINOR 1
////////////////////////////////////////////////////////////
// Identify the operating system
// see http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system
////////////////////////////////////////////////////////////
#if defined(_WIN32)
// Windows
#define SFML_SYSTEM_WINDOWS
#ifndef NOMINMAX
#define NOMINMAX
#endif
#elif defined(__APPLE__) && defined(__MACH__)
// Apple platform, see which one it is
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
// iOS
#define SFML_SYSTEM_IOS
#elif TARGET_OS_MAC
// MacOS
#define SFML_SYSTEM_MACOS
#else
// Unsupported Apple system
#error This Apple operating system is not supported by SFML library
#endif
#elif defined(__unix__)
// UNIX system, see which one it is
#if defined(__ANDROID__)
// Android
#define SFML_SYSTEM_ANDROID
#elif defined(__linux__)
// Linux
#define SFML_SYSTEM_LINUX
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
// FreeBSD
#define SFML_SYSTEM_FREEBSD
#else
// Unsupported UNIX system
#error This UNIX operating system is not supported by SFML library
#endif
#else
// Unsupported system
#error This operating system is not supported by SFML library
#endif
////////////////////////////////////////////////////////////
// Define a portable debug macro
////////////////////////////////////////////////////////////
#if !defined(NDEBUG)
#define SFML_DEBUG
#endif
////////////////////////////////////////////////////////////
// Define helpers to create portable import / export macros for each module
////////////////////////////////////////////////////////////
#if !defined(SFML_STATIC)
#if defined(SFML_SYSTEM_WINDOWS)
// Windows compilers need specific (and different) keywords for export and import
#define SFML_API_EXPORT __declspec(dllexport)
#define SFML_API_IMPORT __declspec(dllimport)
// For Visual C++ compilers, we also need to turn off this annoying C4251 warning
#ifdef _MSC_VER
#pragma warning(disable : 4251)
#endif
#else // Linux, FreeBSD, Mac OS X
#if __GNUC__ >= 4
// GCC 4 has special keywords for showing/hidding symbols,
// the same keyword is used for both importing and exporting
#define SFML_API_EXPORT __attribute__ ((__visibility__ ("default")))
#define SFML_API_IMPORT __attribute__ ((__visibility__ ("default")))
#else
// GCC < 4 has no mechanism to explicitely hide symbols, everything's exported
#define SFML_API_EXPORT
#define SFML_API_IMPORT
#endif
#endif
#else
// Static build doesn't need import/export macros
#define SFML_API_EXPORT
#define SFML_API_IMPORT
#endif
////////////////////////////////////////////////////////////
// Define portable fixed-size types
////////////////////////////////////////////////////////////
namespace sf
{
// All "common" platforms use the same size for char, short and int
// (basically there are 3 types for 3 sizes, so no other match is possible),
// we can use them without doing any kind of check
// 8 bits integer types
typedef signed char Int8;
typedef unsigned char Uint8;
// 16 bits integer types
typedef signed short Int16;
typedef unsigned short Uint16;
// 32 bits integer types
typedef signed int Int32;
typedef unsigned int Uint32;
// 64 bits integer types
#if defined(_MSC_VER)
typedef signed __int64 Int64;
typedef unsigned __int64 Uint64;
#else
typedef signed long long Int64;
typedef unsigned long long Uint64;
#endif
} // namespace sf
#endif // SFML_CONFIG_HPP
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_CONFIG_HPP
#define SFML_CONFIG_HPP
////////////////////////////////////////////////////////////
// Define the SFML version
////////////////////////////////////////////////////////////
#define SFML_VERSION_MAJOR 2
#define SFML_VERSION_MINOR 1
////////////////////////////////////////////////////////////
// Identify the operating system
// see http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system
////////////////////////////////////////////////////////////
#if defined(_WIN32)
// Windows
#define SFML_SYSTEM_WINDOWS
#ifndef NOMINMAX
#define NOMINMAX
#endif
#elif defined(__APPLE__) && defined(__MACH__)
// Apple platform, see which one it is
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
// iOS
#define SFML_SYSTEM_IOS
#elif TARGET_OS_MAC
// MacOS
#define SFML_SYSTEM_MACOS
#else
// Unsupported Apple system
#error This Apple operating system is not supported by SFML library
#endif
#elif defined(__unix__)
// UNIX system, see which one it is
#if defined(__ANDROID__)
// Android
#define SFML_SYSTEM_ANDROID
#elif defined(__linux__)
// Linux
#define SFML_SYSTEM_LINUX
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
// FreeBSD
#define SFML_SYSTEM_FREEBSD
#else
// Unsupported UNIX system
#error This UNIX operating system is not supported by SFML library
#endif
#else
// Unsupported system
#error This operating system is not supported by SFML library
#endif
////////////////////////////////////////////////////////////
// Define a portable debug macro
////////////////////////////////////////////////////////////
#if !defined(NDEBUG)
#define SFML_DEBUG
#endif
////////////////////////////////////////////////////////////
// Define helpers to create portable import / export macros for each module
////////////////////////////////////////////////////////////
#if !defined(SFML_STATIC)
#if defined(SFML_SYSTEM_WINDOWS)
// Windows compilers need specific (and different) keywords for export and import
#define SFML_API_EXPORT __declspec(dllexport)
#define SFML_API_IMPORT __declspec(dllimport)
// For Visual C++ compilers, we also need to turn off this annoying C4251 warning
#ifdef _MSC_VER
#pragma warning(disable: 4251)
#endif
#else // Linux, FreeBSD, Mac OS X
#if __GNUC__ >= 4
// GCC 4 has special keywords for showing/hidding symbols,
// the same keyword is used for both importing and exporting
#define SFML_API_EXPORT __attribute__ ((__visibility__ ("default")))
#define SFML_API_IMPORT __attribute__ ((__visibility__ ("default")))
#else
// GCC < 4 has no mechanism to explicitely hide symbols, everything's exported
#define SFML_API_EXPORT
#define SFML_API_IMPORT
#endif
#endif
#else
// Static build doesn't need import/export macros
#define SFML_API_EXPORT
#define SFML_API_IMPORT
#endif
////////////////////////////////////////////////////////////
// Define portable fixed-size types
////////////////////////////////////////////////////////////
namespace sf
{
// All "common" platforms use the same size for char, short and int
// (basically there are 3 types for 3 sizes, so no other match is possible),
// we can use them without doing any kind of check
// 8 bits integer types
typedef signed char Int8;
typedef unsigned char Uint8;
// 16 bits integer types
typedef signed short Int16;
typedef unsigned short Uint16;
// 32 bits integer types
typedef signed int Int32;
typedef unsigned int Uint32;
// 64 bits integer types
#if defined(_MSC_VER)
typedef signed __int64 Int64;
typedef unsigned __int64 Uint64;
#else
typedef signed long long Int64;
typedef unsigned long long Uint64;
#endif
} // namespace sf
#endif // SFML_CONFIG_HPP

View file

@ -1,62 +1,62 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_GRAPHICS_HPP
#define SFML_GRAPHICS_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window.hpp>
#include <SFML/Graphics/BlendMode.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/Glyph.hpp>
#include <SFML/Graphics/Image.hpp>
#include <SFML/Graphics/RenderStates.hpp>
#include <SFML/Graphics/RenderTexture.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Shader.hpp>
#include <SFML/Graphics/Shape.hpp>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/ConvexShape.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Text.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Transform.hpp>
#include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/Graphics/View.hpp>
#endif // SFML_GRAPHICS_HPP
////////////////////////////////////////////////////////////
/// \defgroup graphics Graphics module
///
/// 2D graphics module: sprites, text, shapes, ...
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_GRAPHICS_HPP
#define SFML_GRAPHICS_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window.hpp>
#include <SFML/Graphics/BlendMode.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/Glyph.hpp>
#include <SFML/Graphics/Image.hpp>
#include <SFML/Graphics/RenderStates.hpp>
#include <SFML/Graphics/RenderTexture.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Shader.hpp>
#include <SFML/Graphics/Shape.hpp>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/ConvexShape.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Text.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Transform.hpp>
#include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/Graphics/View.hpp>
#endif // SFML_GRAPHICS_HPP
////////////////////////////////////////////////////////////
/// \defgroup graphics Graphics module
///
/// 2D graphics module: sprites, text, shapes, ...
///
////////////////////////////////////////////////////////////

View file

@ -40,7 +40,7 @@ namespace sf
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API CircleShape : public Shape
{
public :
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
@ -106,7 +106,7 @@ public :
////////////////////////////////////////////////////////////
virtual Vector2f getPoint(unsigned int index) const;
private :
private:
////////////////////////////////////////////////////////////
// Member data

View file

@ -1,259 +1,259 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_COLOR_HPP
#define SFML_COLOR_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility class for manpulating RGBA colors
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Color
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Constructs an opaque black color. It is equivalent to
/// sf::Color(0, 0, 0, 255).
///
////////////////////////////////////////////////////////////
Color();
////////////////////////////////////////////////////////////
/// \brief Construct the color from its 4 RGBA components
///
/// \param red Red component (in the range [0, 255])
/// \param green Green component (in the range [0, 255])
/// \param blue Blue component (in the range [0, 255])
/// \param alpha Alpha (opacity) component (in the range [0, 255])
///
////////////////////////////////////////////////////////////
Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha = 255);
////////////////////////////////////////////////////////////
// Static member data
////////////////////////////////////////////////////////////
static const Color Black; ///< Black predefined color
static const Color White; ///< White predefined color
static const Color Red; ///< Red predefined color
static const Color Green; ///< Green predefined color
static const Color Blue; ///< Blue predefined color
static const Color Yellow; ///< Yellow predefined color
static const Color Magenta; ///< Magenta predefined color
static const Color Cyan; ///< Cyan predefined color
static const Color Transparent; ///< Transparent (black) predefined color
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Uint8 r; ///< Red component
Uint8 g; ///< Green component
Uint8 b; ///< Blue component
Uint8 a; ///< Alpha (opacity) component
};
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the == operator
///
/// This operator compares two colors and check if they are equal.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return True if colors are equal, false if they are different
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API bool operator ==(const Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the != operator
///
/// This operator compares two colors and check if they are different.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return True if colors are different, false if they are equal
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API bool operator !=(const Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary + operator
///
/// This operator returns the component-wise sum of two colors.
/// Components that exceed 255 are clamped to 255.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Result of \a left + \a right
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color operator +(const Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary - operator
///
/// This operator returns the component-wise subtraction of two colors.
/// Components below 0 are clamped to 0.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Result of \a left - \a right
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color operator -(const Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary * operator
///
/// This operator returns the component-wise multiplication
/// (also called "modulation") of two colors.
/// Components are then divided by 255 so that the result is
/// still in the range [0, 255].
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Result of \a left * \a right
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color operator *(const Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary += operator
///
/// This operator computes the component-wise sum of two colors,
/// and assigns the result to the left operand.
/// Components that exceed 255 are clamped to 255.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color& operator +=(Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary -= operator
///
/// This operator computes the component-wise subtraction of two colors,
/// and assigns the result to the left operand.
/// Components below 0 are clamped to 0.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color& operator -=(Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary *= operator
///
/// This operator returns the component-wise multiplication
/// (also called "modulation") of two colors, and assigns
/// the result to the left operand.
/// Components are then divided by 255 so that the result is
/// still in the range [0, 255].
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color& operator *=(Color& left, const Color& right);
} // namespace sf
#endif // SFML_COLOR_HPP
////////////////////////////////////////////////////////////
/// \class sf::Color
/// \ingroup graphics
///
/// sf::Color is a simple color class composed of 4 components:
/// \li Red
/// \li Green
/// \li Blue
/// \li Alpha (opacity)
///
/// Each component is a public member, an unsigned integer in
/// the range [0, 255]. Thus, colors can be constructed and
/// manipulated very easily:
///
/// \code
/// sf::Color color(255, 0, 0); // red
/// color.r = 0; // make it black
/// color.b = 128; // make it dark blue
/// \endcode
///
/// The fourth component of colors, named "alpha", represents
/// the opacity of the color. A color with an alpha value of
/// 255 will be fully opaque, while an alpha value of 0 will
/// make a color fully transparent, whatever the value of the
/// other components is.
///
/// The most common colors are already defined as static variables:
/// \code
/// sf::Color black = sf::Color::Black;
/// sf::Color white = sf::Color::White;
/// sf::Color red = sf::Color::Red;
/// sf::Color green = sf::Color::Green;
/// sf::Color blue = sf::Color::Blue;
/// sf::Color yellow = sf::Color::Yellow;
/// sf::Color magenta = sf::Color::Magenta;
/// sf::Color cyan = sf::Color::Cyan;
/// sf::Color transparent = sf::Color::Transparent;
/// \endcode
///
/// Colors can also be added and modulated (multiplied) using the
/// overloaded operators + and *.
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_COLOR_HPP
#define SFML_COLOR_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility class for manpulating RGBA colors
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Color
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Constructs an opaque black color. It is equivalent to
/// sf::Color(0, 0, 0, 255).
///
////////////////////////////////////////////////////////////
Color();
////////////////////////////////////////////////////////////
/// \brief Construct the color from its 4 RGBA components
///
/// \param red Red component (in the range [0, 255])
/// \param green Green component (in the range [0, 255])
/// \param blue Blue component (in the range [0, 255])
/// \param alpha Alpha (opacity) component (in the range [0, 255])
///
////////////////////////////////////////////////////////////
Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha = 255);
////////////////////////////////////////////////////////////
// Static member data
////////////////////////////////////////////////////////////
static const Color Black; ///< Black predefined color
static const Color White; ///< White predefined color
static const Color Red; ///< Red predefined color
static const Color Green; ///< Green predefined color
static const Color Blue; ///< Blue predefined color
static const Color Yellow; ///< Yellow predefined color
static const Color Magenta; ///< Magenta predefined color
static const Color Cyan; ///< Cyan predefined color
static const Color Transparent; ///< Transparent (black) predefined color
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Uint8 r; ///< Red component
Uint8 g; ///< Green component
Uint8 b; ///< Blue component
Uint8 a; ///< Alpha (opacity) component
};
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the == operator
///
/// This operator compares two colors and check if they are equal.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return True if colors are equal, false if they are different
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API bool operator ==(const Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the != operator
///
/// This operator compares two colors and check if they are different.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return True if colors are different, false if they are equal
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API bool operator !=(const Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary + operator
///
/// This operator returns the component-wise sum of two colors.
/// Components that exceed 255 are clamped to 255.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Result of \a left + \a right
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color operator +(const Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary - operator
///
/// This operator returns the component-wise subtraction of two colors.
/// Components below 0 are clamped to 0.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Result of \a left - \a right
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color operator -(const Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary * operator
///
/// This operator returns the component-wise multiplication
/// (also called "modulation") of two colors.
/// Components are then divided by 255 so that the result is
/// still in the range [0, 255].
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Result of \a left * \a right
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color operator *(const Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary += operator
///
/// This operator computes the component-wise sum of two colors,
/// and assigns the result to the left operand.
/// Components that exceed 255 are clamped to 255.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color& operator +=(Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary -= operator
///
/// This operator computes the component-wise subtraction of two colors,
/// and assigns the result to the left operand.
/// Components below 0 are clamped to 0.
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color& operator -=(Color& left, const Color& right);
////////////////////////////////////////////////////////////
/// \relates Color
/// \brief Overload of the binary *= operator
///
/// This operator returns the component-wise multiplication
/// (also called "modulation") of two colors, and assigns
/// the result to the left operand.
/// Components are then divided by 255 so that the result is
/// still in the range [0, 255].
///
/// \param left Left operand
/// \param right Right operand
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
SFML_GRAPHICS_API Color& operator *=(Color& left, const Color& right);
} // namespace sf
#endif // SFML_COLOR_HPP
////////////////////////////////////////////////////////////
/// \class sf::Color
/// \ingroup graphics
///
/// sf::Color is a simple color class composed of 4 components:
/// \li Red
/// \li Green
/// \li Blue
/// \li Alpha (opacity)
///
/// Each component is a public member, an unsigned integer in
/// the range [0, 255]. Thus, colors can be constructed and
/// manipulated very easily:
///
/// \code
/// sf::Color color(255, 0, 0); // red
/// color.r = 0; // make it black
/// color.b = 128; // make it dark blue
/// \endcode
///
/// The fourth component of colors, named "alpha", represents
/// the opacity of the color. A color with an alpha value of
/// 255 will be fully opaque, while an alpha value of 0 will
/// make a color fully transparent, whatever the value of the
/// other components is.
///
/// The most common colors are already defined as static variables:
/// \code
/// sf::Color black = sf::Color::Black;
/// sf::Color white = sf::Color::White;
/// sf::Color red = sf::Color::Red;
/// sf::Color green = sf::Color::Green;
/// sf::Color blue = sf::Color::Blue;
/// sf::Color yellow = sf::Color::Yellow;
/// sf::Color magenta = sf::Color::Magenta;
/// sf::Color cyan = sf::Color::Cyan;
/// sf::Color transparent = sf::Color::Transparent;
/// \endcode
///
/// Colors can also be added and modulated (multiplied) using the
/// overloaded operators + and *.
///
////////////////////////////////////////////////////////////

View file

@ -41,7 +41,7 @@ namespace sf
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API ConvexShape : public Shape
{
public :
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
@ -107,7 +107,7 @@ public :
////////////////////////////////////////////////////////////
virtual Vector2f getPoint(unsigned int index) const;
private :
private:
////////////////////////////////////////////////////////////
// Member data

View file

@ -1,126 +1,126 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_DRAWABLE_HPP
#define SFML_DRAWABLE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/RenderStates.hpp>
namespace sf
{
class RenderTarget;
////////////////////////////////////////////////////////////
/// \brief Abstract base class for objects that can be drawn
/// to a render target
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Drawable
{
public :
////////////////////////////////////////////////////////////
/// \brief Virtual destructor
///
////////////////////////////////////////////////////////////
virtual ~Drawable() {}
protected :
friend class RenderTarget;
////////////////////////////////////////////////////////////
/// \brief Draw the object to a render target
///
/// This is a pure virtual function that has to be implemented
/// by the derived class to define how the drawable should be
/// drawn.
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const = 0;
};
} // namespace sf
#endif // SFML_DRAWABLE_HPP
////////////////////////////////////////////////////////////
/// \class sf::Drawable
/// \ingroup graphics
///
/// sf::Drawable is a very simple base class that allows objects
/// of derived classes to be drawn to a sf::RenderTarget.
///
/// All you have to do in your derived class is to override the
/// draw virtual function.
///
/// Note that inheriting from sf::Drawable is not mandatory,
/// but it allows this nice syntax "window.draw(object)" rather
/// than "object.draw(window)", which is more consistent with other
/// SFML classes.
///
/// Example:
/// \code
/// class MyDrawable : public sf::Drawable
/// {
/// public :
///
/// ...
///
/// private :
///
/// virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
/// {
/// // You can draw other high-level objects
/// target.draw(m_sprite, states);
///
/// // ... or use the low-level API
/// states.texture = &m_texture;
/// target.draw(m_vertices, states);
///
/// // ... or draw with OpenGL directly
/// glBegin(GL_QUADS);
/// ...
/// glEnd();
/// }
///
/// sf::Sprite m_sprite;
/// sf::Texture m_texture;
/// sf::VertexArray m_vertices;
/// };
/// \endcode
///
/// \see sf::RenderTarget
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_DRAWABLE_HPP
#define SFML_DRAWABLE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/RenderStates.hpp>
namespace sf
{
class RenderTarget;
////////////////////////////////////////////////////////////
/// \brief Abstract base class for objects that can be drawn
/// to a render target
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Drawable
{
public:
////////////////////////////////////////////////////////////
/// \brief Virtual destructor
///
////////////////////////////////////////////////////////////
virtual ~Drawable() {}
protected:
friend class RenderTarget;
////////////////////////////////////////////////////////////
/// \brief Draw the object to a render target
///
/// This is a pure virtual function that has to be implemented
/// by the derived class to define how the drawable should be
/// drawn.
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const = 0;
};
} // namespace sf
#endif // SFML_DRAWABLE_HPP
////////////////////////////////////////////////////////////
/// \class sf::Drawable
/// \ingroup graphics
///
/// sf::Drawable is a very simple base class that allows objects
/// of derived classes to be drawn to a sf::RenderTarget.
///
/// All you have to do in your derived class is to override the
/// draw virtual function.
///
/// Note that inheriting from sf::Drawable is not mandatory,
/// but it allows this nice syntax "window.draw(object)" rather
/// than "object.draw(window)", which is more consistent with other
/// SFML classes.
///
/// Example:
/// \code
/// class MyDrawable : public sf::Drawable
/// {
/// public:
///
/// ...
///
/// private:
///
/// virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
/// {
/// // You can draw other high-level objects
/// target.draw(m_sprite, states);
///
/// // ... or use the low-level API
/// states.texture = &m_texture;
/// target.draw(m_vertices, states);
///
/// // ... or draw with OpenGL directly
/// glBegin(GL_QUADS);
/// ...
/// glEnd();
/// }
///
/// sf::Sprite m_sprite;
/// sf::Texture m_texture;
/// sf::VertexArray m_vertices;
/// };
/// \endcode
///
/// \see sf::RenderTarget
///
////////////////////////////////////////////////////////////

View file

@ -1,423 +1,423 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_FONT_HPP
#define SFML_FONT_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Glyph.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/String.hpp>
#include <map>
#include <string>
#include <vector>
namespace sf
{
class InputStream;
////////////////////////////////////////////////////////////
/// \brief Class for loading and manipulating character fonts
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Font
{
public :
////////////////////////////////////////////////////////////
/// \brief Holds various information about a font
///
////////////////////////////////////////////////////////////
struct Info
{
std::string family; ///< The font family
};
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor defines an empty font
///
////////////////////////////////////////////////////////////
Font();
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
Font(const Font& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// Cleans up all the internal resources used by the font
///
////////////////////////////////////////////////////////////
~Font();
////////////////////////////////////////////////////////////
/// \brief Load the font from a file
///
/// The supported font formats are: TrueType, Type 1, CFF,
/// OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42.
/// Note that this function know nothing about the standard
/// fonts installed on the user's system, thus you can't
/// load them directly.
///
/// \param filename Path of the font file to load
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromMemory, loadFromStream
///
////////////////////////////////////////////////////////////
bool loadFromFile(const std::string& filename);
////////////////////////////////////////////////////////////
/// \brief Load the font from a file in memory
///
/// The supported font formats are: TrueType, Type 1, CFF,
/// OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42.
/// Warning: SFML cannot preload all the font data in this
/// function, so the buffer pointed by \a data has to remain
/// valid as long as the font is used.
///
/// \param data Pointer to the file data in memory
/// \param sizeInBytes Size of the data to load, in bytes
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromFile, loadFromStream
///
////////////////////////////////////////////////////////////
bool loadFromMemory(const void* data, std::size_t sizeInBytes);
////////////////////////////////////////////////////////////
/// \brief Load the font from a custom stream
///
/// The supported font formats are: TrueType, Type 1, CFF,
/// OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42.
/// Warning: SFML cannot preload all the font data in this
/// function, so the contents of \a stream have to remain
/// valid as long as the font is used.
///
/// \param stream Source stream to read from
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromFile, loadFromMemory
///
////////////////////////////////////////////////////////////
bool loadFromStream(InputStream& stream);
////////////////////////////////////////////////////////////
/// \brief Get the font information
///
/// \return A structure that holds the font information
///
////////////////////////////////////////////////////////////
const Info& getInfo() const;
////////////////////////////////////////////////////////////
/// \brief Retrieve a glyph of the font
///
/// If the font is a bitmap font, not all character sizes
/// might be available. If the glyph is not available at the
/// requested size, an empty glyph is returned.
///
/// \param codePoint Unicode code point of the character to get
/// \param characterSize Reference character size
/// \param bold Retrieve the bold version or the regular one?
///
/// \return The glyph corresponding to \a codePoint and \a characterSize
///
////////////////////////////////////////////////////////////
const Glyph& getGlyph(Uint32 codePoint, unsigned int characterSize, bool bold) const;
////////////////////////////////////////////////////////////
/// \brief Get the kerning offset of two glyphs
///
/// The kerning is an extra offset (negative) to apply between two
/// glyphs when rendering them, to make the pair look more "natural".
/// For example, the pair "AV" have a special kerning to make them
/// closer than other characters. Most of the glyphs pairs have a
/// kerning offset of zero, though.
///
/// \param first Unicode code point of the first character
/// \param second Unicode code point of the second character
/// \param characterSize Reference character size
///
/// \return Kerning value for \a first and \a second, in pixels
///
////////////////////////////////////////////////////////////
float getKerning(Uint32 first, Uint32 second, unsigned int characterSize) const;
////////////////////////////////////////////////////////////
/// \brief Get the line spacing
///
/// Line spacing is the vertical offset to apply between two
/// consecutive lines of text.
///
/// \param characterSize Reference character size
///
/// \return Line spacing, in pixels
///
////////////////////////////////////////////////////////////
float getLineSpacing(unsigned int characterSize) const;
////////////////////////////////////////////////////////////
/// \brief Get the position of the underline
///
/// Underline position is the vertical offset to apply between the
/// baseline and the underline.
///
/// \param characterSize Reference character size
///
/// \return Underline position, in pixels
///
/// \see getUnderlineThickness
///
////////////////////////////////////////////////////////////
float getUnderlinePosition(unsigned int characterSize) const;
////////////////////////////////////////////////////////////
/// \brief Get the thickness of the underline
///
/// Underline thickness is the vertical size of the underline.
///
/// \param characterSize Reference character size
///
/// \return Underline thickness, in pixels
///
/// \see getUnderlinePosition
///
////////////////////////////////////////////////////////////
float getUnderlineThickness(unsigned int characterSize) const;
////////////////////////////////////////////////////////////
/// \brief Retrieve the texture containing the loaded glyphs of a certain size
///
/// The contents of the returned texture changes as more glyphs
/// are requested, thus it is not very relevant. It is mainly
/// used internally by sf::Text.
///
/// \param characterSize Reference character size
///
/// \return Texture containing the glyphs of the requested size
///
////////////////////////////////////////////////////////////
const Texture& getTexture(unsigned int characterSize) const;
////////////////////////////////////////////////////////////
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
Font& operator =(const Font& right);
private :
////////////////////////////////////////////////////////////
/// \brief Structure defining a row of glyphs
///
////////////////////////////////////////////////////////////
struct Row
{
Row(unsigned int rowTop, unsigned int rowHeight) : width(0), top(rowTop), height(rowHeight) {}
unsigned int width; ///< Current width of the row
unsigned int top; ///< Y position of the row into the texture
unsigned int height; ///< Height of the row
};
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::map<Uint32, Glyph> GlyphTable; ///< Table mapping a codepoint to its glyph
////////////////////////////////////////////////////////////
/// \brief Structure defining a page of glyphs
///
////////////////////////////////////////////////////////////
struct Page
{
Page();
GlyphTable glyphs; ///< Table mapping code points to their corresponding glyph
sf::Texture texture; ///< Texture containing the pixels of the glyphs
unsigned int nextRow; ///< Y position of the next new row in the texture
std::vector<Row> rows; ///< List containing the position of all the existing rows
};
////////////////////////////////////////////////////////////
/// \brief Free all the internal resources
///
////////////////////////////////////////////////////////////
void cleanup();
////////////////////////////////////////////////////////////
/// \brief Load a new glyph and store it in the cache
///
/// \param codePoint Unicode code point of the character to load
/// \param characterSize Reference character size
/// \param bold Retrieve the bold version or the regular one?
///
/// \return The glyph corresponding to \a codePoint and \a characterSize
///
////////////////////////////////////////////////////////////
Glyph loadGlyph(Uint32 codePoint, unsigned int characterSize, bool bold) const;
////////////////////////////////////////////////////////////
/// \brief Find a suitable rectangle within the texture for a glyph
///
/// \param page Page of glyphs to search in
/// \param width Width of the rectangle
/// \param height Height of the rectangle
///
/// \return Found rectangle within the texture
///
////////////////////////////////////////////////////////////
IntRect findGlyphRect(Page& page, unsigned int width, unsigned int height) const;
////////////////////////////////////////////////////////////
/// \brief Make sure that the given size is the current one
///
/// \param characterSize Reference character size
///
/// \return True on success, false if any error happened
///
////////////////////////////////////////////////////////////
bool setCurrentSize(unsigned int characterSize) const;
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::map<unsigned int, Page> PageTable; ///< Table mapping a character size to its page (texture)
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
void* m_library; ///< Pointer to the internal library interface (it is typeless to avoid exposing implementation details)
void* m_face; ///< Pointer to the internal font face (it is typeless to avoid exposing implementation details)
void* m_streamRec; ///< Pointer to the stream rec instance (it is typeless to avoid exposing implementation details)
int* m_refCount; ///< Reference counter used by implicit sharing
Info m_info; ///< Information about the font
mutable PageTable m_pages; ///< Table containing the glyphs pages by character size
mutable std::vector<Uint8> m_pixelBuffer; ///< Pixel buffer holding a glyph's pixels before being written to the texture
#ifdef SFML_SYSTEM_ANDROID
void* m_stream; ///< Asset file streamer (if loaded from file)
#endif
};
} // namespace sf
#endif // SFML_FONT_HPP
////////////////////////////////////////////////////////////
/// \class sf::Font
/// \ingroup graphics
///
/// Fonts can be loaded from a file, from memory or from a custom
/// stream, and supports the most common types of fonts. See
/// the loadFromFile function for the complete list of supported formats.
///
/// Once it is loaded, a sf::Font instance provides three
/// types of information about the font:
/// \li Global metrics, such as the line spacing
/// \li Per-glyph metrics, such as bounding box or kerning
/// \li Pixel representation of glyphs
///
/// Fonts alone are not very useful: they hold the font data
/// but cannot make anything useful of it. To do so you need to
/// use the sf::Text class, which is able to properly output text
/// with several options such as character size, style, color,
/// position, rotation, etc.
/// This separation allows more flexibility and better performances:
/// indeed a sf::Font is a heavy resource, and any operation on it
/// is slow (often too slow for real-time applications). On the other
/// side, a sf::Text is a lightweight object which can combine the
/// glyphs data and metrics of a sf::Font to display any text on a
/// render target.
/// Note that it is also possible to bind several sf::Text instances
/// to the same sf::Font.
///
/// It is important to note that the sf::Text instance doesn't
/// copy the font that it uses, it only keeps a reference to it.
/// Thus, a sf::Font must not be destructed while it is
/// used by a sf::Text (i.e. never write a function that
/// uses a local sf::Font instance for creating a text).
///
/// Usage example:
/// \code
/// // Declare a new font
/// sf::Font font;
///
/// // Load it from a file
/// if (!font.loadFromFile("arial.ttf"))
/// {
/// // error...
/// }
///
/// // Create a text which uses our font
/// sf::Text text1;
/// text1.setFont(font);
/// text1.setCharacterSize(30);
/// text1.setStyle(sf::Text::Regular);
///
/// // Create another text using the same font, but with different parameters
/// sf::Text text2;
/// text2.setFont(font);
/// text2.setCharacterSize(50);
/// text1.setStyle(sf::Text::Italic);
/// \endcode
///
/// Apart from loading font files, and passing them to instances
/// of sf::Text, you should normally not have to deal directly
/// with this class. However, it may be useful to access the
/// font metrics or rasterized glyphs for advanced usage.
///
/// Note that if the font is a bitmap font, it is not scalable,
/// thus not all requested sizes will be available to use. This
/// needs to be taken into consideration when using sf::Text.
/// If you need to display text of a certain size, make sure the
/// corresponding bitmap font that supports that size is used.
///
/// \see sf::Text
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_FONT_HPP
#define SFML_FONT_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Glyph.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/String.hpp>
#include <map>
#include <string>
#include <vector>
namespace sf
{
class InputStream;
////////////////////////////////////////////////////////////
/// \brief Class for loading and manipulating character fonts
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Font
{
public:
////////////////////////////////////////////////////////////
/// \brief Holds various information about a font
///
////////////////////////////////////////////////////////////
struct Info
{
std::string family; ///< The font family
};
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor defines an empty font
///
////////////////////////////////////////////////////////////
Font();
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
Font(const Font& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// Cleans up all the internal resources used by the font
///
////////////////////////////////////////////////////////////
~Font();
////////////////////////////////////////////////////////////
/// \brief Load the font from a file
///
/// The supported font formats are: TrueType, Type 1, CFF,
/// OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42.
/// Note that this function know nothing about the standard
/// fonts installed on the user's system, thus you can't
/// load them directly.
///
/// \param filename Path of the font file to load
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromMemory, loadFromStream
///
////////////////////////////////////////////////////////////
bool loadFromFile(const std::string& filename);
////////////////////////////////////////////////////////////
/// \brief Load the font from a file in memory
///
/// The supported font formats are: TrueType, Type 1, CFF,
/// OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42.
/// Warning: SFML cannot preload all the font data in this
/// function, so the buffer pointed by \a data has to remain
/// valid as long as the font is used.
///
/// \param data Pointer to the file data in memory
/// \param sizeInBytes Size of the data to load, in bytes
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromFile, loadFromStream
///
////////////////////////////////////////////////////////////
bool loadFromMemory(const void* data, std::size_t sizeInBytes);
////////////////////////////////////////////////////////////
/// \brief Load the font from a custom stream
///
/// The supported font formats are: TrueType, Type 1, CFF,
/// OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42.
/// Warning: SFML cannot preload all the font data in this
/// function, so the contents of \a stream have to remain
/// valid as long as the font is used.
///
/// \param stream Source stream to read from
///
/// \return True if loading succeeded, false if it failed
///
/// \see loadFromFile, loadFromMemory
///
////////////////////////////////////////////////////////////
bool loadFromStream(InputStream& stream);
////////////////////////////////////////////////////////////
/// \brief Get the font information
///
/// \return A structure that holds the font information
///
////////////////////////////////////////////////////////////
const Info& getInfo() const;
////////////////////////////////////////////////////////////
/// \brief Retrieve a glyph of the font
///
/// If the font is a bitmap font, not all character sizes
/// might be available. If the glyph is not available at the
/// requested size, an empty glyph is returned.
///
/// \param codePoint Unicode code point of the character to get
/// \param characterSize Reference character size
/// \param bold Retrieve the bold version or the regular one?
///
/// \return The glyph corresponding to \a codePoint and \a characterSize
///
////////////////////////////////////////////////////////////
const Glyph& getGlyph(Uint32 codePoint, unsigned int characterSize, bool bold) const;
////////////////////////////////////////////////////////////
/// \brief Get the kerning offset of two glyphs
///
/// The kerning is an extra offset (negative) to apply between two
/// glyphs when rendering them, to make the pair look more "natural".
/// For example, the pair "AV" have a special kerning to make them
/// closer than other characters. Most of the glyphs pairs have a
/// kerning offset of zero, though.
///
/// \param first Unicode code point of the first character
/// \param second Unicode code point of the second character
/// \param characterSize Reference character size
///
/// \return Kerning value for \a first and \a second, in pixels
///
////////////////////////////////////////////////////////////
float getKerning(Uint32 first, Uint32 second, unsigned int characterSize) const;
////////////////////////////////////////////////////////////
/// \brief Get the line spacing
///
/// Line spacing is the vertical offset to apply between two
/// consecutive lines of text.
///
/// \param characterSize Reference character size
///
/// \return Line spacing, in pixels
///
////////////////////////////////////////////////////////////
float getLineSpacing(unsigned int characterSize) const;
////////////////////////////////////////////////////////////
/// \brief Get the position of the underline
///
/// Underline position is the vertical offset to apply between the
/// baseline and the underline.
///
/// \param characterSize Reference character size
///
/// \return Underline position, in pixels
///
/// \see getUnderlineThickness
///
////////////////////////////////////////////////////////////
float getUnderlinePosition(unsigned int characterSize) const;
////////////////////////////////////////////////////////////
/// \brief Get the thickness of the underline
///
/// Underline thickness is the vertical size of the underline.
///
/// \param characterSize Reference character size
///
/// \return Underline thickness, in pixels
///
/// \see getUnderlinePosition
///
////////////////////////////////////////////////////////////
float getUnderlineThickness(unsigned int characterSize) const;
////////////////////////////////////////////////////////////
/// \brief Retrieve the texture containing the loaded glyphs of a certain size
///
/// The contents of the returned texture changes as more glyphs
/// are requested, thus it is not very relevant. It is mainly
/// used internally by sf::Text.
///
/// \param characterSize Reference character size
///
/// \return Texture containing the glyphs of the requested size
///
////////////////////////////////////////////////////////////
const Texture& getTexture(unsigned int characterSize) const;
////////////////////////////////////////////////////////////
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
Font& operator =(const Font& right);
private:
////////////////////////////////////////////////////////////
/// \brief Structure defining a row of glyphs
///
////////////////////////////////////////////////////////////
struct Row
{
Row(unsigned int rowTop, unsigned int rowHeight) : width(0), top(rowTop), height(rowHeight) {}
unsigned int width; ///< Current width of the row
unsigned int top; ///< Y position of the row into the texture
unsigned int height; ///< Height of the row
};
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::map<Uint32, Glyph> GlyphTable; ///< Table mapping a codepoint to its glyph
////////////////////////////////////////////////////////////
/// \brief Structure defining a page of glyphs
///
////////////////////////////////////////////////////////////
struct Page
{
Page();
GlyphTable glyphs; ///< Table mapping code points to their corresponding glyph
sf::Texture texture; ///< Texture containing the pixels of the glyphs
unsigned int nextRow; ///< Y position of the next new row in the texture
std::vector<Row> rows; ///< List containing the position of all the existing rows
};
////////////////////////////////////////////////////////////
/// \brief Free all the internal resources
///
////////////////////////////////////////////////////////////
void cleanup();
////////////////////////////////////////////////////////////
/// \brief Load a new glyph and store it in the cache
///
/// \param codePoint Unicode code point of the character to load
/// \param characterSize Reference character size
/// \param bold Retrieve the bold version or the regular one?
///
/// \return The glyph corresponding to \a codePoint and \a characterSize
///
////////////////////////////////////////////////////////////
Glyph loadGlyph(Uint32 codePoint, unsigned int characterSize, bool bold) const;
////////////////////////////////////////////////////////////
/// \brief Find a suitable rectangle within the texture for a glyph
///
/// \param page Page of glyphs to search in
/// \param width Width of the rectangle
/// \param height Height of the rectangle
///
/// \return Found rectangle within the texture
///
////////////////////////////////////////////////////////////
IntRect findGlyphRect(Page& page, unsigned int width, unsigned int height) const;
////////////////////////////////////////////////////////////
/// \brief Make sure that the given size is the current one
///
/// \param characterSize Reference character size
///
/// \return True on success, false if any error happened
///
////////////////////////////////////////////////////////////
bool setCurrentSize(unsigned int characterSize) const;
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::map<unsigned int, Page> PageTable; ///< Table mapping a character size to its page (texture)
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
void* m_library; ///< Pointer to the internal library interface (it is typeless to avoid exposing implementation details)
void* m_face; ///< Pointer to the internal font face (it is typeless to avoid exposing implementation details)
void* m_streamRec; ///< Pointer to the stream rec instance (it is typeless to avoid exposing implementation details)
int* m_refCount; ///< Reference counter used by implicit sharing
Info m_info; ///< Information about the font
mutable PageTable m_pages; ///< Table containing the glyphs pages by character size
mutable std::vector<Uint8> m_pixelBuffer; ///< Pixel buffer holding a glyph's pixels before being written to the texture
#ifdef SFML_SYSTEM_ANDROID
void* m_stream; ///< Asset file streamer (if loaded from file)
#endif
};
} // namespace sf
#endif // SFML_FONT_HPP
////////////////////////////////////////////////////////////
/// \class sf::Font
/// \ingroup graphics
///
/// Fonts can be loaded from a file, from memory or from a custom
/// stream, and supports the most common types of fonts. See
/// the loadFromFile function for the complete list of supported formats.
///
/// Once it is loaded, a sf::Font instance provides three
/// types of information about the font:
/// \li Global metrics, such as the line spacing
/// \li Per-glyph metrics, such as bounding box or kerning
/// \li Pixel representation of glyphs
///
/// Fonts alone are not very useful: they hold the font data
/// but cannot make anything useful of it. To do so you need to
/// use the sf::Text class, which is able to properly output text
/// with several options such as character size, style, color,
/// position, rotation, etc.
/// This separation allows more flexibility and better performances:
/// indeed a sf::Font is a heavy resource, and any operation on it
/// is slow (often too slow for real-time applications). On the other
/// side, a sf::Text is a lightweight object which can combine the
/// glyphs data and metrics of a sf::Font to display any text on a
/// render target.
/// Note that it is also possible to bind several sf::Text instances
/// to the same sf::Font.
///
/// It is important to note that the sf::Text instance doesn't
/// copy the font that it uses, it only keeps a reference to it.
/// Thus, a sf::Font must not be destructed while it is
/// used by a sf::Text (i.e. never write a function that
/// uses a local sf::Font instance for creating a text).
///
/// Usage example:
/// \code
/// // Declare a new font
/// sf::Font font;
///
/// // Load it from a file
/// if (!font.loadFromFile("arial.ttf"))
/// {
/// // error...
/// }
///
/// // Create a text which uses our font
/// sf::Text text1;
/// text1.setFont(font);
/// text1.setCharacterSize(30);
/// text1.setStyle(sf::Text::Regular);
///
/// // Create another text using the same font, but with different parameters
/// sf::Text text2;
/// text2.setFont(font);
/// text2.setCharacterSize(50);
/// text1.setStyle(sf::Text::Italic);
/// \endcode
///
/// Apart from loading font files, and passing them to instances
/// of sf::Text, you should normally not have to deal directly
/// with this class. However, it may be useful to access the
/// font metrics or rasterized glyphs for advanced usage.
///
/// Note that if the font is a bitmap font, it is not scalable,
/// thus not all requested sizes will be available to use. This
/// needs to be taken into consideration when using sf::Text.
/// If you need to display text of a certain size, make sure the
/// corresponding bitmap font that supports that size is used.
///
/// \see sf::Text
///
////////////////////////////////////////////////////////////

View file

@ -1,79 +1,79 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_GLYPH_HPP
#define SFML_GLYPH_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Rect.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Structure describing a glyph
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Glyph
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Glyph() : advance(0) {}
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
float advance; ///< Offset to move horizontically to the next character
FloatRect bounds; ///< Bounding rectangle of the glyph, in coordinates relative to the baseline
IntRect textureRect; ///< Texture coordinates of the glyph inside the font's texture
};
} // namespace sf
#endif // SFML_GLYPH_HPP
////////////////////////////////////////////////////////////
/// \class sf::Glyph
/// \ingroup graphics
///
/// A glyph is the visual representation of a character.
///
/// The sf::Glyph structure provides the information needed
/// to handle the glyph:
/// \li its coordinates in the font's texture
/// \li its bounding rectangle
/// \li the offset to apply to get the starting position of the next glyph
///
/// \see sf::Font
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_GLYPH_HPP
#define SFML_GLYPH_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Rect.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Structure describing a glyph
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Glyph
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Glyph() : advance(0) {}
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
float advance; ///< Offset to move horizontically to the next character
FloatRect bounds; ///< Bounding rectangle of the glyph, in coordinates relative to the baseline
IntRect textureRect; ///< Texture coordinates of the glyph inside the font's texture
};
} // namespace sf
#endif // SFML_GLYPH_HPP
////////////////////////////////////////////////////////////
/// \class sf::Glyph
/// \ingroup graphics
///
/// A glyph is the visual representation of a character.
///
/// The sf::Glyph structure provides the information needed
/// to handle the glyph:
/// \li its coordinates in the font's texture
/// \li its bounding rectangle
/// \li the offset to apply to get the starting position of the next glyph
///
/// \see sf::Font
///
////////////////////////////////////////////////////////////

View file

@ -1,327 +1,327 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_IMAGE_HPP
#define SFML_IMAGE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <string>
#include <vector>
namespace sf
{
class InputStream;
////////////////////////////////////////////////////////////
/// \brief Class for loading, manipulating and saving images
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Image
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty image.
///
////////////////////////////////////////////////////////////
Image();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~Image();
////////////////////////////////////////////////////////////
/// \brief Create the image and fill it with a unique color
///
/// \param width Width of the image
/// \param height Height of the image
/// \param color Fill color
///
////////////////////////////////////////////////////////////
void create(unsigned int width, unsigned int height, const Color& color = Color(0, 0, 0));
////////////////////////////////////////////////////////////
/// \brief Create the image from an array of pixels
///
/// The \a pixel array is assumed to contain 32-bits RGBA pixels,
/// and have the given \a width and \a height. If not, this is
/// an undefined behaviour.
/// If \a pixels is null, an empty image is created.
///
/// \param width Width of the image
/// \param height Height of the image
/// \param pixels Array of pixels to copy to the image
///
////////////////////////////////////////////////////////////
void create(unsigned int width, unsigned int height, const Uint8* pixels);
////////////////////////////////////////////////////////////
/// \brief Load the image from a file on disk
///
/// The supported image formats are bmp, png, tga, jpg, gif,
/// psd, hdr and pic. Some format options are not supported,
/// like progressive jpeg.
/// If this function fails, the image is left unchanged.
///
/// \param filename Path of the image file to load
///
/// \return True if loading was successful
///
/// \see loadFromMemory, loadFromStream, saveToFile
///
////////////////////////////////////////////////////////////
bool loadFromFile(const std::string& filename);
////////////////////////////////////////////////////////////
/// \brief Load the image from a file in memory
///
/// The supported image formats are bmp, png, tga, jpg, gif,
/// psd, hdr and pic. Some format options are not supported,
/// like progressive jpeg.
/// If this function fails, the image is left unchanged.
///
/// \param data Pointer to the file data in memory
/// \param size Size of the data to load, in bytes
///
/// \return True if loading was successful
///
/// \see loadFromFile, loadFromStream
///
////////////////////////////////////////////////////////////
bool loadFromMemory(const void* data, std::size_t size);
////////////////////////////////////////////////////////////
/// \brief Load the image from a custom stream
///
/// The supported image formats are bmp, png, tga, jpg, gif,
/// psd, hdr and pic. Some format options are not supported,
/// like progressive jpeg.
/// If this function fails, the image is left unchanged.
///
/// \param stream Source stream to read from
///
/// \return True if loading was successful
///
/// \see loadFromFile, loadFromMemory
///
////////////////////////////////////////////////////////////
bool loadFromStream(InputStream& stream);
////////////////////////////////////////////////////////////
/// \brief Save the image to a file on disk
///
/// The format of the image is automatically deduced from
/// the extension. The supported image formats are bmp, png,
/// tga and jpg. The destination file is overwritten
/// if it already exists. This function fails if the image is empty.
///
/// \param filename Path of the file to save
///
/// \return True if saving was successful
///
/// \see create, loadFromFile, loadFromMemory
///
////////////////////////////////////////////////////////////
bool saveToFile(const std::string& filename) const;
////////////////////////////////////////////////////////////
/// \brief Return the size (width and height) of the image
///
/// \return Size of the image, in pixels
///
////////////////////////////////////////////////////////////
Vector2u getSize() const;
////////////////////////////////////////////////////////////
/// \brief Create a transparency mask from a specified color-key
///
/// This function sets the alpha value of every pixel matching
/// the given color to \a alpha (0 by default), so that they
/// become transparent.
///
/// \param color Color to make transparent
/// \param alpha Alpha value to assign to transparent pixels
///
////////////////////////////////////////////////////////////
void createMaskFromColor(const Color& color, Uint8 alpha = 0);
////////////////////////////////////////////////////////////
/// \brief Copy pixels from another image onto this one
///
/// This function does a slow pixel copy and should not be
/// used intensively. It can be used to prepare a complex
/// static image from several others, but if you need this
/// kind of feature in real-time you'd better use sf::RenderTexture.
///
/// If \a sourceRect is empty, the whole image is copied.
/// If \a applyAlpha is set to true, the transparency of
/// source pixels is applied. If it is false, the pixels are
/// copied unchanged with their alpha value.
///
/// \param source Source image to copy
/// \param destX X coordinate of the destination position
/// \param destY Y coordinate of the destination position
/// \param sourceRect Sub-rectangle of the source image to copy
/// \param applyAlpha Should the copy take in account the source transparency?
///
////////////////////////////////////////////////////////////
void copy(const Image& source, unsigned int destX, unsigned int destY, const IntRect& sourceRect = IntRect(0, 0, 0, 0), bool applyAlpha = false);
////////////////////////////////////////////////////////////
/// \brief Change the color of a pixel
///
/// This function doesn't check the validity of the pixel
/// coordinates, using out-of-range values will result in
/// an undefined behaviour.
///
/// \param x X coordinate of pixel to change
/// \param y Y coordinate of pixel to change
/// \param color New color of the pixel
///
/// \see getPixel
///
////////////////////////////////////////////////////////////
void setPixel(unsigned int x, unsigned int y, const Color& color);
////////////////////////////////////////////////////////////
/// \brief Get the color of a pixel
///
/// This function doesn't check the validity of the pixel
/// coordinates, using out-of-range values will result in
/// an undefined behaviour.
///
/// \param x X coordinate of pixel to get
/// \param y Y coordinate of pixel to get
///
/// \return Color of the pixel at coordinates (x, y)
///
/// \see setPixel
///
////////////////////////////////////////////////////////////
Color getPixel(unsigned int x, unsigned int y) const;
////////////////////////////////////////////////////////////
/// \brief Get a read-only pointer to the array of pixels
///
/// The returned value points to an array of RGBA pixels made of
/// 8 bits integers components. The size of the array is
/// width * height * 4 (getSize().x * getSize().y * 4).
/// Warning: the returned pointer may become invalid if you
/// modify the image, so you should never store it for too long.
/// If the image is empty, a null pointer is returned.
///
/// \return Read-only pointer to the array of pixels
///
////////////////////////////////////////////////////////////
const Uint8* getPixelsPtr() const;
////////////////////////////////////////////////////////////
/// \brief Flip the image horizontally (left <-> right)
///
////////////////////////////////////////////////////////////
void flipHorizontally();
////////////////////////////////////////////////////////////
/// \brief Flip the image vertically (top <-> bottom)
///
////////////////////////////////////////////////////////////
void flipVertically();
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Vector2u m_size; ///< Image size
std::vector<Uint8> m_pixels; ///< Pixels of the image
#ifdef SFML_SYSTEM_ANDROID
void* m_stream; ///< Asset file streamer (if loaded from file)
#endif
};
} // namespace sf
#endif // SFML_IMAGE_HPP
////////////////////////////////////////////////////////////
/// \class sf::Image
/// \ingroup graphics
///
/// sf::Image is an abstraction to manipulate images
/// as bidimensional arrays of pixels. The class provides
/// functions to load, read, write and save pixels, as well
/// as many other useful functions.
///
/// sf::Image can handle a unique internal representation of
/// pixels, which is RGBA 32 bits. This means that a pixel
/// must be composed of 8 bits red, green, blue and alpha
/// channels -- just like a sf::Color.
/// All the functions that return an array of pixels follow
/// this rule, and all parameters that you pass to sf::Image
/// functions (such as loadFromMemory) must use this
/// representation as well.
///
/// A sf::Image can be copied, but it is a heavy resource and
/// if possible you should always use [const] references to
/// pass or return them to avoid useless copies.
///
/// Usage example:
/// \code
/// // Load an image file from a file
/// sf::Image background;
/// if (!background.loadFromFile("background.jpg"))
/// return -1;
///
/// // Create a 20x20 image filled with black color
/// sf::Image image;
/// image.create(20, 20, sf::Color::Black);
///
/// // Copy image1 on image2 at position (10, 10)
/// image.copy(background, 10, 10);
///
/// // Make the top-left pixel transparent
/// sf::Color color = image.getPixel(0, 0);
/// color.a = 0;
/// image.setPixel(0, 0, color);
///
/// // Save the image to a file
/// if (!image.saveToFile("result.png"))
/// return -1;
/// \endcode
///
/// \see sf::Texture
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_IMAGE_HPP
#define SFML_IMAGE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <string>
#include <vector>
namespace sf
{
class InputStream;
////////////////////////////////////////////////////////////
/// \brief Class for loading, manipulating and saving images
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Image
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty image.
///
////////////////////////////////////////////////////////////
Image();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~Image();
////////////////////////////////////////////////////////////
/// \brief Create the image and fill it with a unique color
///
/// \param width Width of the image
/// \param height Height of the image
/// \param color Fill color
///
////////////////////////////////////////////////////////////
void create(unsigned int width, unsigned int height, const Color& color = Color(0, 0, 0));
////////////////////////////////////////////////////////////
/// \brief Create the image from an array of pixels
///
/// The \a pixel array is assumed to contain 32-bits RGBA pixels,
/// and have the given \a width and \a height. If not, this is
/// an undefined behaviour.
/// If \a pixels is null, an empty image is created.
///
/// \param width Width of the image
/// \param height Height of the image
/// \param pixels Array of pixels to copy to the image
///
////////////////////////////////////////////////////////////
void create(unsigned int width, unsigned int height, const Uint8* pixels);
////////////////////////////////////////////////////////////
/// \brief Load the image from a file on disk
///
/// The supported image formats are bmp, png, tga, jpg, gif,
/// psd, hdr and pic. Some format options are not supported,
/// like progressive jpeg.
/// If this function fails, the image is left unchanged.
///
/// \param filename Path of the image file to load
///
/// \return True if loading was successful
///
/// \see loadFromMemory, loadFromStream, saveToFile
///
////////////////////////////////////////////////////////////
bool loadFromFile(const std::string& filename);
////////////////////////////////////////////////////////////
/// \brief Load the image from a file in memory
///
/// The supported image formats are bmp, png, tga, jpg, gif,
/// psd, hdr and pic. Some format options are not supported,
/// like progressive jpeg.
/// If this function fails, the image is left unchanged.
///
/// \param data Pointer to the file data in memory
/// \param size Size of the data to load, in bytes
///
/// \return True if loading was successful
///
/// \see loadFromFile, loadFromStream
///
////////////////////////////////////////////////////////////
bool loadFromMemory(const void* data, std::size_t size);
////////////////////////////////////////////////////////////
/// \brief Load the image from a custom stream
///
/// The supported image formats are bmp, png, tga, jpg, gif,
/// psd, hdr and pic. Some format options are not supported,
/// like progressive jpeg.
/// If this function fails, the image is left unchanged.
///
/// \param stream Source stream to read from
///
/// \return True if loading was successful
///
/// \see loadFromFile, loadFromMemory
///
////////////////////////////////////////////////////////////
bool loadFromStream(InputStream& stream);
////////////////////////////////////////////////////////////
/// \brief Save the image to a file on disk
///
/// The format of the image is automatically deduced from
/// the extension. The supported image formats are bmp, png,
/// tga and jpg. The destination file is overwritten
/// if it already exists. This function fails if the image is empty.
///
/// \param filename Path of the file to save
///
/// \return True if saving was successful
///
/// \see create, loadFromFile, loadFromMemory
///
////////////////////////////////////////////////////////////
bool saveToFile(const std::string& filename) const;
////////////////////////////////////////////////////////////
/// \brief Return the size (width and height) of the image
///
/// \return Size of the image, in pixels
///
////////////////////////////////////////////////////////////
Vector2u getSize() const;
////////////////////////////////////////////////////////////
/// \brief Create a transparency mask from a specified color-key
///
/// This function sets the alpha value of every pixel matching
/// the given color to \a alpha (0 by default), so that they
/// become transparent.
///
/// \param color Color to make transparent
/// \param alpha Alpha value to assign to transparent pixels
///
////////////////////////////////////////////////////////////
void createMaskFromColor(const Color& color, Uint8 alpha = 0);
////////////////////////////////////////////////////////////
/// \brief Copy pixels from another image onto this one
///
/// This function does a slow pixel copy and should not be
/// used intensively. It can be used to prepare a complex
/// static image from several others, but if you need this
/// kind of feature in real-time you'd better use sf::RenderTexture.
///
/// If \a sourceRect is empty, the whole image is copied.
/// If \a applyAlpha is set to true, the transparency of
/// source pixels is applied. If it is false, the pixels are
/// copied unchanged with their alpha value.
///
/// \param source Source image to copy
/// \param destX X coordinate of the destination position
/// \param destY Y coordinate of the destination position
/// \param sourceRect Sub-rectangle of the source image to copy
/// \param applyAlpha Should the copy take in account the source transparency?
///
////////////////////////////////////////////////////////////
void copy(const Image& source, unsigned int destX, unsigned int destY, const IntRect& sourceRect = IntRect(0, 0, 0, 0), bool applyAlpha = false);
////////////////////////////////////////////////////////////
/// \brief Change the color of a pixel
///
/// This function doesn't check the validity of the pixel
/// coordinates, using out-of-range values will result in
/// an undefined behaviour.
///
/// \param x X coordinate of pixel to change
/// \param y Y coordinate of pixel to change
/// \param color New color of the pixel
///
/// \see getPixel
///
////////////////////////////////////////////////////////////
void setPixel(unsigned int x, unsigned int y, const Color& color);
////////////////////////////////////////////////////////////
/// \brief Get the color of a pixel
///
/// This function doesn't check the validity of the pixel
/// coordinates, using out-of-range values will result in
/// an undefined behaviour.
///
/// \param x X coordinate of pixel to get
/// \param y Y coordinate of pixel to get
///
/// \return Color of the pixel at coordinates (x, y)
///
/// \see setPixel
///
////////////////////////////////////////////////////////////
Color getPixel(unsigned int x, unsigned int y) const;
////////////////////////////////////////////////////////////
/// \brief Get a read-only pointer to the array of pixels
///
/// The returned value points to an array of RGBA pixels made of
/// 8 bits integers components. The size of the array is
/// width * height * 4 (getSize().x * getSize().y * 4).
/// Warning: the returned pointer may become invalid if you
/// modify the image, so you should never store it for too long.
/// If the image is empty, a null pointer is returned.
///
/// \return Read-only pointer to the array of pixels
///
////////////////////////////////////////////////////////////
const Uint8* getPixelsPtr() const;
////////////////////////////////////////////////////////////
/// \brief Flip the image horizontally (left <-> right)
///
////////////////////////////////////////////////////////////
void flipHorizontally();
////////////////////////////////////////////////////////////
/// \brief Flip the image vertically (top <-> bottom)
///
////////////////////////////////////////////////////////////
void flipVertically();
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Vector2u m_size; ///< Image size
std::vector<Uint8> m_pixels; ///< Pixels of the image
#ifdef SFML_SYSTEM_ANDROID
void* m_stream; ///< Asset file streamer (if loaded from file)
#endif
};
} // namespace sf
#endif // SFML_IMAGE_HPP
////////////////////////////////////////////////////////////
/// \class sf::Image
/// \ingroup graphics
///
/// sf::Image is an abstraction to manipulate images
/// as bidimensional arrays of pixels. The class provides
/// functions to load, read, write and save pixels, as well
/// as many other useful functions.
///
/// sf::Image can handle a unique internal representation of
/// pixels, which is RGBA 32 bits. This means that a pixel
/// must be composed of 8 bits red, green, blue and alpha
/// channels -- just like a sf::Color.
/// All the functions that return an array of pixels follow
/// this rule, and all parameters that you pass to sf::Image
/// functions (such as loadFromMemory) must use this
/// representation as well.
///
/// A sf::Image can be copied, but it is a heavy resource and
/// if possible you should always use [const] references to
/// pass or return them to avoid useless copies.
///
/// Usage example:
/// \code
/// // Load an image file from a file
/// sf::Image background;
/// if (!background.loadFromFile("background.jpg"))
/// return -1;
///
/// // Create a 20x20 image filled with black color
/// sf::Image image;
/// image.create(20, 20, sf::Color::Black);
///
/// // Copy image1 on image2 at position (10, 10)
/// image.copy(background, 10, 10);
///
/// // Make the top-left pixel transparent
/// sf::Color color = image.getPixel(0, 0);
/// color.a = 0;
/// image.setPixel(0, 0, color);
///
/// // Save the image to a file
/// if (!image.saveToFile("result.png"))
/// return -1;
/// \endcode
///
/// \see sf::Texture
///
////////////////////////////////////////////////////////////

View file

@ -1,248 +1,248 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RECT_HPP
#define SFML_RECT_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Vector2.hpp>
#include <algorithm>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility class for manipulating 2D axis aligned rectangles
///
////////////////////////////////////////////////////////////
template <typename T>
class Rect
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty rectangle (it is equivalent to calling
/// Rect(0, 0, 0, 0)).
///
////////////////////////////////////////////////////////////
Rect();
////////////////////////////////////////////////////////////
/// \brief Construct the rectangle from its coordinates
///
/// Be careful, the last two parameters are the width
/// and height, not the right and bottom coordinates!
///
/// \param rectLeft Left coordinate of the rectangle
/// \param rectTop Top coordinate of the rectangle
/// \param rectWidth Width of the rectangle
/// \param rectHeight Height of the rectangle
///
////////////////////////////////////////////////////////////
Rect(T rectLeft, T rectTop, T rectWidth, T rectHeight);
////////////////////////////////////////////////////////////
/// \brief Construct the rectangle from position and size
///
/// Be careful, the last parameter is the size,
/// not the bottom-right corner!
///
/// \param position Position of the top-left corner of the rectangle
/// \param size Size of the rectangle
///
////////////////////////////////////////////////////////////
Rect(const Vector2<T>& position, const Vector2<T>& size);
////////////////////////////////////////////////////////////
/// \brief Construct the rectangle from another type of rectangle
///
/// This constructor doesn't replace the copy constructor,
/// it's called only when U != T.
/// A call to this constructor will fail to compile if U
/// is not convertible to T.
///
/// \param rectangle Rectangle to convert
///
////////////////////////////////////////////////////////////
template <typename U>
explicit Rect(const Rect<U>& rectangle);
////////////////////////////////////////////////////////////
/// \brief Check if a point is inside the rectangle's area
///
/// \param x X coordinate of the point to test
/// \param y Y coordinate of the point to test
///
/// \return True if the point is inside, false otherwise
///
/// \see intersects
///
////////////////////////////////////////////////////////////
bool contains(T x, T y) const;
////////////////////////////////////////////////////////////
/// \brief Check if a point is inside the rectangle's area
///
/// \param point Point to test
///
/// \return True if the point is inside, false otherwise
///
/// \see intersects
///
////////////////////////////////////////////////////////////
bool contains(const Vector2<T>& point) const;
////////////////////////////////////////////////////////////
/// \brief Check the intersection between two rectangles
///
/// \param rectangle Rectangle to test
///
/// \return True if rectangles overlap, false otherwise
///
/// \see contains
///
////////////////////////////////////////////////////////////
bool intersects(const Rect<T>& rectangle) const;
////////////////////////////////////////////////////////////
/// \brief Check the intersection between two rectangles
///
/// This overload returns the overlapped rectangle in the
/// \a intersection parameter.
///
/// \param rectangle Rectangle to test
/// \param intersection Rectangle to be filled with the intersection
///
/// \return True if rectangles overlap, false otherwise
///
/// \see contains
///
////////////////////////////////////////////////////////////
bool intersects(const Rect<T>& rectangle, Rect<T>& intersection) const;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
T left; ///< Left coordinate of the rectangle
T top; ///< Top coordinate of the rectangle
T width; ///< Width of the rectangle
T height; ///< Height of the rectangle
};
////////////////////////////////////////////////////////////
/// \relates Rect
/// \brief Overload of binary operator ==
///
/// This operator compares strict equality between two rectangles.
///
/// \param left Left operand (a rectangle)
/// \param right Right operand (a rectangle)
///
/// \return True if \a left is equal to \a right
///
////////////////////////////////////////////////////////////
template <typename T>
bool operator ==(const Rect<T>& left, const Rect<T>& right);
////////////////////////////////////////////////////////////
/// \relates Rect
/// \brief Overload of binary operator !=
///
/// This operator compares strict difference between two rectangles.
///
/// \param left Left operand (a rectangle)
/// \param right Right operand (a rectangle)
///
/// \return True if \a left is not equal to \a right
///
////////////////////////////////////////////////////////////
template <typename T>
bool operator !=(const Rect<T>& left, const Rect<T>& right);
#include <SFML/Graphics/Rect.inl>
// Create typedefs for the most common types
typedef Rect<int> IntRect;
typedef Rect<float> FloatRect;
} // namespace sf
#endif // SFML_RECT_HPP
////////////////////////////////////////////////////////////
/// \class sf::Rect
/// \ingroup graphics
///
/// A rectangle is defined by its top-left corner and its size.
/// It is a very simple class defined for convenience, so
/// its member variables (left, top, width and height) are public
/// and can be accessed directly, just like the vector classes
/// (Vector2 and Vector3).
///
/// To keep things simple, sf::Rect doesn't define
/// functions to emulate the properties that are not directly
/// members (such as right, bottom, center, etc.), it rather
/// only provides intersection functions.
///
/// sf::Rect uses the usual rules for its boundaries:
/// \li The left and top edges are included in the rectangle's area
/// \li The right (left + width) and bottom (top + height) edges are excluded from the rectangle's area
///
/// This means that sf::IntRect(0, 0, 1, 1) and sf::IntRect(1, 1, 1, 1)
/// don't intersect.
///
/// sf::Rect is a template and may be used with any numeric type, but
/// for simplicity the instanciations used by SFML are typedefed:
/// \li sf::Rect<int> is sf::IntRect
/// \li sf::Rect<float> is sf::FloatRect
///
/// So that you don't have to care about the template syntax.
///
/// Usage example:
/// \code
/// // Define a rectangle, located at (0, 0) with a size of 20x5
/// sf::IntRect r1(0, 0, 20, 5);
///
/// // Define another rectangle, located at (4, 2) with a size of 18x10
/// sf::Vector2i position(4, 2);
/// sf::Vector2i size(18, 10);
/// sf::IntRect r2(position, size);
///
/// // Test intersections with the point (3, 1)
/// bool b1 = r1.contains(3, 1); // true
/// bool b2 = r2.contains(3, 1); // false
///
/// // Test the intersection between r1 and r2
/// sf::IntRect result;
/// bool b3 = r1.intersects(r2, result); // true
/// // result == (4, 2, 16, 3)
/// \endcode
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RECT_HPP
#define SFML_RECT_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Vector2.hpp>
#include <algorithm>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility class for manipulating 2D axis aligned rectangles
///
////////////////////////////////////////////////////////////
template <typename T>
class Rect
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty rectangle (it is equivalent to calling
/// Rect(0, 0, 0, 0)).
///
////////////////////////////////////////////////////////////
Rect();
////////////////////////////////////////////////////////////
/// \brief Construct the rectangle from its coordinates
///
/// Be careful, the last two parameters are the width
/// and height, not the right and bottom coordinates!
///
/// \param rectLeft Left coordinate of the rectangle
/// \param rectTop Top coordinate of the rectangle
/// \param rectWidth Width of the rectangle
/// \param rectHeight Height of the rectangle
///
////////////////////////////////////////////////////////////
Rect(T rectLeft, T rectTop, T rectWidth, T rectHeight);
////////////////////////////////////////////////////////////
/// \brief Construct the rectangle from position and size
///
/// Be careful, the last parameter is the size,
/// not the bottom-right corner!
///
/// \param position Position of the top-left corner of the rectangle
/// \param size Size of the rectangle
///
////////////////////////////////////////////////////////////
Rect(const Vector2<T>& position, const Vector2<T>& size);
////////////////////////////////////////////////////////////
/// \brief Construct the rectangle from another type of rectangle
///
/// This constructor doesn't replace the copy constructor,
/// it's called only when U != T.
/// A call to this constructor will fail to compile if U
/// is not convertible to T.
///
/// \param rectangle Rectangle to convert
///
////////////////////////////////////////////////////////////
template <typename U>
explicit Rect(const Rect<U>& rectangle);
////////////////////////////////////////////////////////////
/// \brief Check if a point is inside the rectangle's area
///
/// \param x X coordinate of the point to test
/// \param y Y coordinate of the point to test
///
/// \return True if the point is inside, false otherwise
///
/// \see intersects
///
////////////////////////////////////////////////////////////
bool contains(T x, T y) const;
////////////////////////////////////////////////////////////
/// \brief Check if a point is inside the rectangle's area
///
/// \param point Point to test
///
/// \return True if the point is inside, false otherwise
///
/// \see intersects
///
////////////////////////////////////////////////////////////
bool contains(const Vector2<T>& point) const;
////////////////////////////////////////////////////////////
/// \brief Check the intersection between two rectangles
///
/// \param rectangle Rectangle to test
///
/// \return True if rectangles overlap, false otherwise
///
/// \see contains
///
////////////////////////////////////////////////////////////
bool intersects(const Rect<T>& rectangle) const;
////////////////////////////////////////////////////////////
/// \brief Check the intersection between two rectangles
///
/// This overload returns the overlapped rectangle in the
/// \a intersection parameter.
///
/// \param rectangle Rectangle to test
/// \param intersection Rectangle to be filled with the intersection
///
/// \return True if rectangles overlap, false otherwise
///
/// \see contains
///
////////////////////////////////////////////////////////////
bool intersects(const Rect<T>& rectangle, Rect<T>& intersection) const;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
T left; ///< Left coordinate of the rectangle
T top; ///< Top coordinate of the rectangle
T width; ///< Width of the rectangle
T height; ///< Height of the rectangle
};
////////////////////////////////////////////////////////////
/// \relates Rect
/// \brief Overload of binary operator ==
///
/// This operator compares strict equality between two rectangles.
///
/// \param left Left operand (a rectangle)
/// \param right Right operand (a rectangle)
///
/// \return True if \a left is equal to \a right
///
////////////////////////////////////////////////////////////
template <typename T>
bool operator ==(const Rect<T>& left, const Rect<T>& right);
////////////////////////////////////////////////////////////
/// \relates Rect
/// \brief Overload of binary operator !=
///
/// This operator compares strict difference between two rectangles.
///
/// \param left Left operand (a rectangle)
/// \param right Right operand (a rectangle)
///
/// \return True if \a left is not equal to \a right
///
////////////////////////////////////////////////////////////
template <typename T>
bool operator !=(const Rect<T>& left, const Rect<T>& right);
#include <SFML/Graphics/Rect.inl>
// Create typedefs for the most common types
typedef Rect<int> IntRect;
typedef Rect<float> FloatRect;
} // namespace sf
#endif // SFML_RECT_HPP
////////////////////////////////////////////////////////////
/// \class sf::Rect
/// \ingroup graphics
///
/// A rectangle is defined by its top-left corner and its size.
/// It is a very simple class defined for convenience, so
/// its member variables (left, top, width and height) are public
/// and can be accessed directly, just like the vector classes
/// (Vector2 and Vector3).
///
/// To keep things simple, sf::Rect doesn't define
/// functions to emulate the properties that are not directly
/// members (such as right, bottom, center, etc.), it rather
/// only provides intersection functions.
///
/// sf::Rect uses the usual rules for its boundaries:
/// \li The left and top edges are included in the rectangle's area
/// \li The right (left + width) and bottom (top + height) edges are excluded from the rectangle's area
///
/// This means that sf::IntRect(0, 0, 1, 1) and sf::IntRect(1, 1, 1, 1)
/// don't intersect.
///
/// sf::Rect is a template and may be used with any numeric type, but
/// for simplicity the instanciations used by SFML are typedefed:
/// \li sf::Rect<int> is sf::IntRect
/// \li sf::Rect<float> is sf::FloatRect
///
/// So that you don't have to care about the template syntax.
///
/// Usage example:
/// \code
/// // Define a rectangle, located at (0, 0) with a size of 20x5
/// sf::IntRect r1(0, 0, 20, 5);
///
/// // Define another rectangle, located at (4, 2) with a size of 18x10
/// sf::Vector2i position(4, 2);
/// sf::Vector2i size(18, 10);
/// sf::IntRect r2(position, size);
///
/// // Test intersections with the point (3, 1)
/// bool b1 = r1.contains(3, 1); // true
/// bool b2 = r2.contains(3, 1); // false
///
/// // Test the intersection between r1 and r2
/// sf::IntRect result;
/// bool b3 = r1.intersects(r2, result); // true
/// // result == (4, 2, 16, 3)
/// \endcode
///
////////////////////////////////////////////////////////////

View file

@ -1,159 +1,159 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
template <typename T>
Rect<T>::Rect() :
left (0),
top (0),
width (0),
height(0)
{
}
////////////////////////////////////////////////////////////
template <typename T>
Rect<T>::Rect(T rectLeft, T rectTop, T rectWidth, T rectHeight) :
left (rectLeft),
top (rectTop),
width (rectWidth),
height(rectHeight)
{
}
////////////////////////////////////////////////////////////
template <typename T>
Rect<T>::Rect(const Vector2<T>& position, const Vector2<T>& size) :
left (position.x),
top (position.y),
width (size.x),
height(size.y)
{
}
////////////////////////////////////////////////////////////
template <typename T>
template <typename U>
Rect<T>::Rect(const Rect<U>& rectangle) :
left (static_cast<T>(rectangle.left)),
top (static_cast<T>(rectangle.top)),
width (static_cast<T>(rectangle.width)),
height(static_cast<T>(rectangle.height))
{
}
////////////////////////////////////////////////////////////
template <typename T>
bool Rect<T>::contains(T x, T y) const
{
// Rectangles with negative dimensions are allowed, so we must handle them correctly
// Compute the real min and max of the rectangle on both axes
T minX = std::min(left, static_cast<T>(left + width));
T maxX = std::max(left, static_cast<T>(left + width));
T minY = std::min(top, static_cast<T>(top + height));
T maxY = std::max(top, static_cast<T>(top + height));
return (x >= minX) && (x < maxX) && (y >= minY) && (y < maxY);
}
////////////////////////////////////////////////////////////
template <typename T>
bool Rect<T>::contains(const Vector2<T>& point) const
{
return contains(point.x, point.y);
}
////////////////////////////////////////////////////////////
template <typename T>
bool Rect<T>::intersects(const Rect<T>& rectangle) const
{
Rect<T> intersection;
return intersects(rectangle, intersection);
}
////////////////////////////////////////////////////////////
template <typename T>
bool Rect<T>::intersects(const Rect<T>& rectangle, Rect<T>& intersection) const
{
// Rectangles with negative dimensions are allowed, so we must handle them correctly
// Compute the min and max of the first rectangle on both axes
T r1MinX = std::min(left, static_cast<T>(left + width));
T r1MaxX = std::max(left, static_cast<T>(left + width));
T r1MinY = std::min(top, static_cast<T>(top + height));
T r1MaxY = std::max(top, static_cast<T>(top + height));
// Compute the min and max of the second rectangle on both axes
T r2MinX = std::min(rectangle.left, static_cast<T>(rectangle.left + rectangle.width));
T r2MaxX = std::max(rectangle.left, static_cast<T>(rectangle.left + rectangle.width));
T r2MinY = std::min(rectangle.top, static_cast<T>(rectangle.top + rectangle.height));
T r2MaxY = std::max(rectangle.top, static_cast<T>(rectangle.top + rectangle.height));
// Compute the intersection boundaries
T interLeft = std::max(r1MinX, r2MinX);
T interTop = std::max(r1MinY, r2MinY);
T interRight = std::min(r1MaxX, r2MaxX);
T interBottom = std::min(r1MaxY, r2MaxY);
// If the intersection is valid (positive non zero area), then there is an intersection
if ((interLeft < interRight) && (interTop < interBottom))
{
intersection = Rect<T>(interLeft, interTop, interRight - interLeft, interBottom - interTop);
return true;
}
else
{
intersection = Rect<T>(0, 0, 0, 0);
return false;
}
}
////////////////////////////////////////////////////////////
template <typename T>
inline bool operator ==(const Rect<T>& left, const Rect<T>& right)
{
return (left.left == right.left) && (left.width == right.width) &&
(left.top == right.top) && (left.height == right.height);
}
////////////////////////////////////////////////////////////
template <typename T>
inline bool operator !=(const Rect<T>& left, const Rect<T>& right)
{
return !(left == right);
}
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
template <typename T>
Rect<T>::Rect() :
left (0),
top (0),
width (0),
height(0)
{
}
////////////////////////////////////////////////////////////
template <typename T>
Rect<T>::Rect(T rectLeft, T rectTop, T rectWidth, T rectHeight) :
left (rectLeft),
top (rectTop),
width (rectWidth),
height(rectHeight)
{
}
////////////////////////////////////////////////////////////
template <typename T>
Rect<T>::Rect(const Vector2<T>& position, const Vector2<T>& size) :
left (position.x),
top (position.y),
width (size.x),
height(size.y)
{
}
////////////////////////////////////////////////////////////
template <typename T>
template <typename U>
Rect<T>::Rect(const Rect<U>& rectangle) :
left (static_cast<T>(rectangle.left)),
top (static_cast<T>(rectangle.top)),
width (static_cast<T>(rectangle.width)),
height(static_cast<T>(rectangle.height))
{
}
////////////////////////////////////////////////////////////
template <typename T>
bool Rect<T>::contains(T x, T y) const
{
// Rectangles with negative dimensions are allowed, so we must handle them correctly
// Compute the real min and max of the rectangle on both axes
T minX = std::min(left, static_cast<T>(left + width));
T maxX = std::max(left, static_cast<T>(left + width));
T minY = std::min(top, static_cast<T>(top + height));
T maxY = std::max(top, static_cast<T>(top + height));
return (x >= minX) && (x < maxX) && (y >= minY) && (y < maxY);
}
////////////////////////////////////////////////////////////
template <typename T>
bool Rect<T>::contains(const Vector2<T>& point) const
{
return contains(point.x, point.y);
}
////////////////////////////////////////////////////////////
template <typename T>
bool Rect<T>::intersects(const Rect<T>& rectangle) const
{
Rect<T> intersection;
return intersects(rectangle, intersection);
}
////////////////////////////////////////////////////////////
template <typename T>
bool Rect<T>::intersects(const Rect<T>& rectangle, Rect<T>& intersection) const
{
// Rectangles with negative dimensions are allowed, so we must handle them correctly
// Compute the min and max of the first rectangle on both axes
T r1MinX = std::min(left, static_cast<T>(left + width));
T r1MaxX = std::max(left, static_cast<T>(left + width));
T r1MinY = std::min(top, static_cast<T>(top + height));
T r1MaxY = std::max(top, static_cast<T>(top + height));
// Compute the min and max of the second rectangle on both axes
T r2MinX = std::min(rectangle.left, static_cast<T>(rectangle.left + rectangle.width));
T r2MaxX = std::max(rectangle.left, static_cast<T>(rectangle.left + rectangle.width));
T r2MinY = std::min(rectangle.top, static_cast<T>(rectangle.top + rectangle.height));
T r2MaxY = std::max(rectangle.top, static_cast<T>(rectangle.top + rectangle.height));
// Compute the intersection boundaries
T interLeft = std::max(r1MinX, r2MinX);
T interTop = std::max(r1MinY, r2MinY);
T interRight = std::min(r1MaxX, r2MaxX);
T interBottom = std::min(r1MaxY, r2MaxY);
// If the intersection is valid (positive non zero area), then there is an intersection
if ((interLeft < interRight) && (interTop < interBottom))
{
intersection = Rect<T>(interLeft, interTop, interRight - interLeft, interBottom - interTop);
return true;
}
else
{
intersection = Rect<T>(0, 0, 0, 0);
return false;
}
}
////////////////////////////////////////////////////////////
template <typename T>
inline bool operator ==(const Rect<T>& left, const Rect<T>& right)
{
return (left.left == right.left) && (left.width == right.width) &&
(left.top == right.top) && (left.height == right.height);
}
////////////////////////////////////////////////////////////
template <typename T>
inline bool operator !=(const Rect<T>& left, const Rect<T>& right)
{
return !(left == right);
}

View file

@ -40,7 +40,7 @@ namespace sf
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RectangleShape : public Shape
{
public :
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
@ -94,7 +94,7 @@ public :
////////////////////////////////////////////////////////////
virtual Vector2f getPoint(unsigned int index) const;
private :
private:
////////////////////////////////////////////////////////////
// Member data

View file

@ -44,7 +44,7 @@ class Texture;
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RenderStates
{
public :
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor

View file

@ -1,451 +1,451 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RENDERTARGET_HPP
#define SFML_RENDERTARGET_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/View.hpp>
#include <SFML/Graphics/Transform.hpp>
#include <SFML/Graphics/BlendMode.hpp>
#include <SFML/Graphics/RenderStates.hpp>
#include <SFML/Graphics/PrimitiveType.hpp>
#include <SFML/Graphics/Vertex.hpp>
#include <SFML/System/NonCopyable.hpp>
namespace sf
{
class Drawable;
////////////////////////////////////////////////////////////
/// \brief Base class for all render targets (window, texture, ...)
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RenderTarget : NonCopyable
{
public :
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~RenderTarget();
////////////////////////////////////////////////////////////
/// \brief Clear the entire target with a single color
///
/// This function is usually called once every frame,
/// to clear the previous contents of the target.
///
/// \param color Fill color to use to clear the render target
///
////////////////////////////////////////////////////////////
void clear(const Color& color = Color(0, 0, 0, 255));
////////////////////////////////////////////////////////////
/// \brief Change the current active view
///
/// The view is like a 2D camera, it controls which part of
/// the 2D scene is visible, and how it is viewed in the
/// render-target.
/// The new view will affect everything that is drawn, until
/// another view is set.
/// The render target keeps its own copy of the view object,
/// so it is not necessary to keep the original one alive
/// after calling this function.
/// To restore the original view of the target, you can pass
/// the result of getDefaultView() to this function.
///
/// \param view New view to use
///
/// \see getView, getDefaultView
///
////////////////////////////////////////////////////////////
void setView(const View& view);
////////////////////////////////////////////////////////////
/// \brief Get the view currently in use in the render target
///
/// \return The view object that is currently used
///
/// \see setView, getDefaultView
///
////////////////////////////////////////////////////////////
const View& getView() const;
////////////////////////////////////////////////////////////
/// \brief Get the default view of the render target
///
/// The default view has the initial size of the render target,
/// and never changes after the target has been created.
///
/// \return The default view of the render target
///
/// \see setView, getView
///
////////////////////////////////////////////////////////////
const View& getDefaultView() const;
////////////////////////////////////////////////////////////
/// \brief Get the viewport of a view, applied to this render target
///
/// The viewport is defined in the view as a ratio, this function
/// simply applies this ratio to the current dimensions of the
/// render target to calculate the pixels rectangle that the viewport
/// actually covers in the target.
///
/// \param view The view for which we want to compute the viewport
///
/// \return Viewport rectangle, expressed in pixels
///
////////////////////////////////////////////////////////////
IntRect getViewport(const View& view) const;
////////////////////////////////////////////////////////////
/// \brief Convert a point from target coordinates to world
/// coordinates, using the current view
///
/// This function is an overload of the mapPixelToCoords
/// function that implicitely uses the current view.
/// It is equivalent to:
/// \code
/// target.mapPixelToCoords(point, target.getView());
/// \endcode
///
/// \param point Pixel to convert
///
/// \return The converted point, in "world" coordinates
///
/// \see mapCoordsToPixel
///
////////////////////////////////////////////////////////////
Vector2f mapPixelToCoords(const Vector2i& point) const;
////////////////////////////////////////////////////////////
/// \brief Convert a point from target coordinates to world coordinates
///
/// This function finds the 2D position that matches the
/// given pixel of the render-target. In other words, it does
/// the inverse of what the graphics card does, to find the
/// initial position of a rendered pixel.
///
/// Initially, both coordinate systems (world units and target pixels)
/// match perfectly. But if you define a custom view or resize your
/// render-target, this assertion is not true anymore, ie. a point
/// located at (10, 50) in your render-target may map to the point
/// (150, 75) in your 2D world -- if the view is translated by (140, 25).
///
/// For render-windows, this function is typically used to find
/// which point (or object) is located below the mouse cursor.
///
/// This version uses a custom view for calculations, see the other
/// overload of the function if you want to use the current view of the
/// render-target.
///
/// \param point Pixel to convert
/// \param view The view to use for converting the point
///
/// \return The converted point, in "world" units
///
/// \see mapCoordsToPixel
///
////////////////////////////////////////////////////////////
Vector2f mapPixelToCoords(const Vector2i& point, const View& view) const;
////////////////////////////////////////////////////////////
/// \brief Convert a point from world coordinates to target
/// coordinates, using the current view
///
/// This function is an overload of the mapCoordsToPixel
/// function that implicitely uses the current view.
/// It is equivalent to:
/// \code
/// target.mapCoordsToPixel(point, target.getView());
/// \endcode
///
/// \param point Point to convert
///
/// \return The converted point, in target coordinates (pixels)
///
/// \see mapPixelToCoords
///
////////////////////////////////////////////////////////////
Vector2i mapCoordsToPixel(const Vector2f& point) const;
////////////////////////////////////////////////////////////
/// \brief Convert a point from world coordinates to target coordinates
///
/// This function finds the pixel of the render-target that matches
/// the given 2D point. In other words, it goes through the same process
/// as the graphics card, to compute the final position of a rendered point.
///
/// Initially, both coordinate systems (world units and target pixels)
/// match perfectly. But if you define a custom view or resize your
/// render-target, this assertion is not true anymore, ie. a point
/// located at (150, 75) in your 2D world may map to the pixel
/// (10, 50) of your render-target -- if the view is translated by (140, 25).
///
/// This version uses a custom view for calculations, see the other
/// overload of the function if you want to use the current view of the
/// render-target.
///
/// \param point Point to convert
/// \param view The view to use for converting the point
///
/// \return The converted point, in target coordinates (pixels)
///
/// \see mapPixelToCoords
///
////////////////////////////////////////////////////////////
Vector2i mapCoordsToPixel(const Vector2f& point, const View& view) const;
////////////////////////////////////////////////////////////
/// \brief Draw a drawable object to the render-target
///
/// \param drawable Object to draw
/// \param states Render states to use for drawing
///
////////////////////////////////////////////////////////////
void draw(const Drawable& drawable, const RenderStates& states = RenderStates::Default);
////////////////////////////////////////////////////////////
/// \brief Draw primitives defined by an array of vertices
///
/// \param vertices Pointer to the vertices
/// \param vertexCount Number of vertices in the array
/// \param type Type of primitives to draw
/// \param states Render states to use for drawing
///
////////////////////////////////////////////////////////////
void draw(const Vertex* vertices, unsigned int vertexCount,
PrimitiveType type, const RenderStates& states = RenderStates::Default);
////////////////////////////////////////////////////////////
/// \brief Return the size of the rendering region of the target
///
/// \return Size in pixels
///
////////////////////////////////////////////////////////////
virtual Vector2u getSize() const = 0;
////////////////////////////////////////////////////////////
/// \brief Save the current OpenGL render states and matrices
///
/// This function can be used when you mix SFML drawing
/// and direct OpenGL rendering. Combined with PopGLStates,
/// it ensures that:
/// \li SFML's internal states are not messed up by your OpenGL code
/// \li your OpenGL states are not modified by a call to a SFML function
///
/// More specifically, it must be used around code that
/// calls Draw functions. Example:
/// \code
/// // OpenGL code here...
/// window.pushGLStates();
/// window.draw(...);
/// window.draw(...);
/// window.popGLStates();
/// // OpenGL code here...
/// \endcode
///
/// Note that this function is quite expensive: it saves all the
/// possible OpenGL states and matrices, even the ones you
/// don't care about. Therefore it should be used wisely.
/// It is provided for convenience, but the best results will
/// be achieved if you handle OpenGL states yourself (because
/// you know which states have really changed, and need to be
/// saved and restored). Take a look at the ResetGLStates
/// function if you do so.
///
/// \see popGLStates
///
////////////////////////////////////////////////////////////
void pushGLStates();
////////////////////////////////////////////////////////////
/// \brief Restore the previously saved OpenGL render states and matrices
///
/// See the description of pushGLStates to get a detailed
/// description of these functions.
///
/// \see pushGLStates
///
////////////////////////////////////////////////////////////
void popGLStates();
////////////////////////////////////////////////////////////
/// \brief Reset the internal OpenGL states so that the target is ready for drawing
///
/// This function can be used when you mix SFML drawing
/// and direct OpenGL rendering, if you choose not to use
/// pushGLStates/popGLStates. It makes sure that all OpenGL
/// states needed by SFML are set, so that subsequent draw()
/// calls will work as expected.
///
/// Example:
/// \code
/// // OpenGL code here...
/// glPushAttrib(...);
/// window.resetGLStates();
/// window.draw(...);
/// window.draw(...);
/// glPopAttrib(...);
/// // OpenGL code here...
/// \endcode
///
////////////////////////////////////////////////////////////
void resetGLStates();
protected :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
RenderTarget();
////////////////////////////////////////////////////////////
/// \brief Performs the common initialization step after creation
///
/// The derived classes must call this function after the
/// target is created and ready for drawing.
///
////////////////////////////////////////////////////////////
void initialize();
private:
////////////////////////////////////////////////////////////
/// \brief Apply the current view
///
////////////////////////////////////////////////////////////
void applyCurrentView();
////////////////////////////////////////////////////////////
/// \brief Apply a new blending mode
///
/// \param mode Blending mode to apply
///
////////////////////////////////////////////////////////////
void applyBlendMode(const BlendMode& mode);
////////////////////////////////////////////////////////////
/// \brief Apply a new transform
///
/// \param transform Transform to apply
///
////////////////////////////////////////////////////////////
void applyTransform(const Transform& transform);
////////////////////////////////////////////////////////////
/// \brief Apply a new texture
///
/// \param texture Texture to apply
///
////////////////////////////////////////////////////////////
void applyTexture(const Texture* texture);
////////////////////////////////////////////////////////////
/// \brief Apply a new shader
///
/// \param shader Shader to apply
///
////////////////////////////////////////////////////////////
void applyShader(const Shader* shader);
////////////////////////////////////////////////////////////
/// \brief Activate the target for rendering
///
/// This function must be implemented by derived classes to make
/// their OpenGL context current; it is called by the base class
/// everytime it's going to use OpenGL calls.
///
/// \param active True to make the target active, false to deactivate it
///
/// \return True if the function succeeded
///
////////////////////////////////////////////////////////////
virtual bool activate(bool active) = 0;
////////////////////////////////////////////////////////////
/// \brief Render states cache
///
////////////////////////////////////////////////////////////
struct StatesCache
{
enum {VertexCacheSize = 4};
bool glStatesSet; ///< Are our internal GL states set yet?
bool viewChanged; ///< Has the current view changed since last draw?
BlendMode lastBlendMode; ///< Cached blending mode
Uint64 lastTextureId; ///< Cached texture
bool useVertexCache; ///< Did we previously use the vertex cache?
Vertex vertexCache[VertexCacheSize]; ///< Pre-transformed vertices cache
};
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
View m_defaultView; ///< Default view
View m_view; ///< Current view
StatesCache m_cache; ///< Render states cache
};
} // namespace sf
#endif // SFML_RENDERTARGET_HPP
////////////////////////////////////////////////////////////
/// \class sf::RenderTarget
/// \ingroup graphics
///
/// sf::RenderTarget defines the common behaviour of all the
/// 2D render targets usable in the graphics module. It makes
/// it possible to draw 2D entities like sprites, shapes, text
/// without using any OpenGL command directly.
///
/// A sf::RenderTarget is also able to use views (sf::View),
/// which are a kind of 2D cameras. With views you can globally
/// scroll, rotate or zoom everything that is drawn,
/// without having to transform every single entity. See the
/// documentation of sf::View for more details and sample pieces of
/// code about this class.
///
/// On top of that, render targets are still able to render direct
/// OpenGL stuff. It is even possible to mix together OpenGL calls
/// and regular SFML drawing commands. When doing so, make sure that
/// OpenGL states are not messed up by calling the
/// pushGLStates/popGLStates functions.
///
/// \see sf::RenderWindow, sf::RenderTexture, sf::View
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RENDERTARGET_HPP
#define SFML_RENDERTARGET_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/View.hpp>
#include <SFML/Graphics/Transform.hpp>
#include <SFML/Graphics/BlendMode.hpp>
#include <SFML/Graphics/RenderStates.hpp>
#include <SFML/Graphics/PrimitiveType.hpp>
#include <SFML/Graphics/Vertex.hpp>
#include <SFML/System/NonCopyable.hpp>
namespace sf
{
class Drawable;
////////////////////////////////////////////////////////////
/// \brief Base class for all render targets (window, texture, ...)
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RenderTarget : NonCopyable
{
public:
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~RenderTarget();
////////////////////////////////////////////////////////////
/// \brief Clear the entire target with a single color
///
/// This function is usually called once every frame,
/// to clear the previous contents of the target.
///
/// \param color Fill color to use to clear the render target
///
////////////////////////////////////////////////////////////
void clear(const Color& color = Color(0, 0, 0, 255));
////////////////////////////////////////////////////////////
/// \brief Change the current active view
///
/// The view is like a 2D camera, it controls which part of
/// the 2D scene is visible, and how it is viewed in the
/// render-target.
/// The new view will affect everything that is drawn, until
/// another view is set.
/// The render target keeps its own copy of the view object,
/// so it is not necessary to keep the original one alive
/// after calling this function.
/// To restore the original view of the target, you can pass
/// the result of getDefaultView() to this function.
///
/// \param view New view to use
///
/// \see getView, getDefaultView
///
////////////////////////////////////////////////////////////
void setView(const View& view);
////////////////////////////////////////////////////////////
/// \brief Get the view currently in use in the render target
///
/// \return The view object that is currently used
///
/// \see setView, getDefaultView
///
////////////////////////////////////////////////////////////
const View& getView() const;
////////////////////////////////////////////////////////////
/// \brief Get the default view of the render target
///
/// The default view has the initial size of the render target,
/// and never changes after the target has been created.
///
/// \return The default view of the render target
///
/// \see setView, getView
///
////////////////////////////////////////////////////////////
const View& getDefaultView() const;
////////////////////////////////////////////////////////////
/// \brief Get the viewport of a view, applied to this render target
///
/// The viewport is defined in the view as a ratio, this function
/// simply applies this ratio to the current dimensions of the
/// render target to calculate the pixels rectangle that the viewport
/// actually covers in the target.
///
/// \param view The view for which we want to compute the viewport
///
/// \return Viewport rectangle, expressed in pixels
///
////////////////////////////////////////////////////////////
IntRect getViewport(const View& view) const;
////////////////////////////////////////////////////////////
/// \brief Convert a point from target coordinates to world
/// coordinates, using the current view
///
/// This function is an overload of the mapPixelToCoords
/// function that implicitely uses the current view.
/// It is equivalent to:
/// \code
/// target.mapPixelToCoords(point, target.getView());
/// \endcode
///
/// \param point Pixel to convert
///
/// \return The converted point, in "world" coordinates
///
/// \see mapCoordsToPixel
///
////////////////////////////////////////////////////////////
Vector2f mapPixelToCoords(const Vector2i& point) const;
////////////////////////////////////////////////////////////
/// \brief Convert a point from target coordinates to world coordinates
///
/// This function finds the 2D position that matches the
/// given pixel of the render-target. In other words, it does
/// the inverse of what the graphics card does, to find the
/// initial position of a rendered pixel.
///
/// Initially, both coordinate systems (world units and target pixels)
/// match perfectly. But if you define a custom view or resize your
/// render-target, this assertion is not true anymore, ie. a point
/// located at (10, 50) in your render-target may map to the point
/// (150, 75) in your 2D world -- if the view is translated by (140, 25).
///
/// For render-windows, this function is typically used to find
/// which point (or object) is located below the mouse cursor.
///
/// This version uses a custom view for calculations, see the other
/// overload of the function if you want to use the current view of the
/// render-target.
///
/// \param point Pixel to convert
/// \param view The view to use for converting the point
///
/// \return The converted point, in "world" units
///
/// \see mapCoordsToPixel
///
////////////////////////////////////////////////////////////
Vector2f mapPixelToCoords(const Vector2i& point, const View& view) const;
////////////////////////////////////////////////////////////
/// \brief Convert a point from world coordinates to target
/// coordinates, using the current view
///
/// This function is an overload of the mapCoordsToPixel
/// function that implicitely uses the current view.
/// It is equivalent to:
/// \code
/// target.mapCoordsToPixel(point, target.getView());
/// \endcode
///
/// \param point Point to convert
///
/// \return The converted point, in target coordinates (pixels)
///
/// \see mapPixelToCoords
///
////////////////////////////////////////////////////////////
Vector2i mapCoordsToPixel(const Vector2f& point) const;
////////////////////////////////////////////////////////////
/// \brief Convert a point from world coordinates to target coordinates
///
/// This function finds the pixel of the render-target that matches
/// the given 2D point. In other words, it goes through the same process
/// as the graphics card, to compute the final position of a rendered point.
///
/// Initially, both coordinate systems (world units and target pixels)
/// match perfectly. But if you define a custom view or resize your
/// render-target, this assertion is not true anymore, ie. a point
/// located at (150, 75) in your 2D world may map to the pixel
/// (10, 50) of your render-target -- if the view is translated by (140, 25).
///
/// This version uses a custom view for calculations, see the other
/// overload of the function if you want to use the current view of the
/// render-target.
///
/// \param point Point to convert
/// \param view The view to use for converting the point
///
/// \return The converted point, in target coordinates (pixels)
///
/// \see mapPixelToCoords
///
////////////////////////////////////////////////////////////
Vector2i mapCoordsToPixel(const Vector2f& point, const View& view) const;
////////////////////////////////////////////////////////////
/// \brief Draw a drawable object to the render-target
///
/// \param drawable Object to draw
/// \param states Render states to use for drawing
///
////////////////////////////////////////////////////////////
void draw(const Drawable& drawable, const RenderStates& states = RenderStates::Default);
////////////////////////////////////////////////////////////
/// \brief Draw primitives defined by an array of vertices
///
/// \param vertices Pointer to the vertices
/// \param vertexCount Number of vertices in the array
/// \param type Type of primitives to draw
/// \param states Render states to use for drawing
///
////////////////////////////////////////////////////////////
void draw(const Vertex* vertices, unsigned int vertexCount,
PrimitiveType type, const RenderStates& states = RenderStates::Default);
////////////////////////////////////////////////////////////
/// \brief Return the size of the rendering region of the target
///
/// \return Size in pixels
///
////////////////////////////////////////////////////////////
virtual Vector2u getSize() const = 0;
////////////////////////////////////////////////////////////
/// \brief Save the current OpenGL render states and matrices
///
/// This function can be used when you mix SFML drawing
/// and direct OpenGL rendering. Combined with PopGLStates,
/// it ensures that:
/// \li SFML's internal states are not messed up by your OpenGL code
/// \li your OpenGL states are not modified by a call to a SFML function
///
/// More specifically, it must be used around code that
/// calls Draw functions. Example:
/// \code
/// // OpenGL code here...
/// window.pushGLStates();
/// window.draw(...);
/// window.draw(...);
/// window.popGLStates();
/// // OpenGL code here...
/// \endcode
///
/// Note that this function is quite expensive: it saves all the
/// possible OpenGL states and matrices, even the ones you
/// don't care about. Therefore it should be used wisely.
/// It is provided for convenience, but the best results will
/// be achieved if you handle OpenGL states yourself (because
/// you know which states have really changed, and need to be
/// saved and restored). Take a look at the ResetGLStates
/// function if you do so.
///
/// \see popGLStates
///
////////////////////////////////////////////////////////////
void pushGLStates();
////////////////////////////////////////////////////////////
/// \brief Restore the previously saved OpenGL render states and matrices
///
/// See the description of pushGLStates to get a detailed
/// description of these functions.
///
/// \see pushGLStates
///
////////////////////////////////////////////////////////////
void popGLStates();
////////////////////////////////////////////////////////////
/// \brief Reset the internal OpenGL states so that the target is ready for drawing
///
/// This function can be used when you mix SFML drawing
/// and direct OpenGL rendering, if you choose not to use
/// pushGLStates/popGLStates. It makes sure that all OpenGL
/// states needed by SFML are set, so that subsequent draw()
/// calls will work as expected.
///
/// Example:
/// \code
/// // OpenGL code here...
/// glPushAttrib(...);
/// window.resetGLStates();
/// window.draw(...);
/// window.draw(...);
/// glPopAttrib(...);
/// // OpenGL code here...
/// \endcode
///
////////////////////////////////////////////////////////////
void resetGLStates();
protected:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
RenderTarget();
////////////////////////////////////////////////////////////
/// \brief Performs the common initialization step after creation
///
/// The derived classes must call this function after the
/// target is created and ready for drawing.
///
////////////////////////////////////////////////////////////
void initialize();
private:
////////////////////////////////////////////////////////////
/// \brief Apply the current view
///
////////////////////////////////////////////////////////////
void applyCurrentView();
////////////////////////////////////////////////////////////
/// \brief Apply a new blending mode
///
/// \param mode Blending mode to apply
///
////////////////////////////////////////////////////////////
void applyBlendMode(const BlendMode& mode);
////////////////////////////////////////////////////////////
/// \brief Apply a new transform
///
/// \param transform Transform to apply
///
////////////////////////////////////////////////////////////
void applyTransform(const Transform& transform);
////////////////////////////////////////////////////////////
/// \brief Apply a new texture
///
/// \param texture Texture to apply
///
////////////////////////////////////////////////////////////
void applyTexture(const Texture* texture);
////////////////////////////////////////////////////////////
/// \brief Apply a new shader
///
/// \param shader Shader to apply
///
////////////////////////////////////////////////////////////
void applyShader(const Shader* shader);
////////////////////////////////////////////////////////////
/// \brief Activate the target for rendering
///
/// This function must be implemented by derived classes to make
/// their OpenGL context current; it is called by the base class
/// everytime it's going to use OpenGL calls.
///
/// \param active True to make the target active, false to deactivate it
///
/// \return True if the function succeeded
///
////////////////////////////////////////////////////////////
virtual bool activate(bool active) = 0;
////////////////////////////////////////////////////////////
/// \brief Render states cache
///
////////////////////////////////////////////////////////////
struct StatesCache
{
enum {VertexCacheSize = 4};
bool glStatesSet; ///< Are our internal GL states set yet?
bool viewChanged; ///< Has the current view changed since last draw?
BlendMode lastBlendMode; ///< Cached blending mode
Uint64 lastTextureId; ///< Cached texture
bool useVertexCache; ///< Did we previously use the vertex cache?
Vertex vertexCache[VertexCacheSize]; ///< Pre-transformed vertices cache
};
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
View m_defaultView; ///< Default view
View m_view; ///< Current view
StatesCache m_cache; ///< Render states cache
};
} // namespace sf
#endif // SFML_RENDERTARGET_HPP
////////////////////////////////////////////////////////////
/// \class sf::RenderTarget
/// \ingroup graphics
///
/// sf::RenderTarget defines the common behaviour of all the
/// 2D render targets usable in the graphics module. It makes
/// it possible to draw 2D entities like sprites, shapes, text
/// without using any OpenGL command directly.
///
/// A sf::RenderTarget is also able to use views (sf::View),
/// which are a kind of 2D cameras. With views you can globally
/// scroll, rotate or zoom everything that is drawn,
/// without having to transform every single entity. See the
/// documentation of sf::View for more details and sample pieces of
/// code about this class.
///
/// On top of that, render targets are still able to render direct
/// OpenGL stuff. It is even possible to mix together OpenGL calls
/// and regular SFML drawing commands. When doing so, make sure that
/// OpenGL states are not messed up by calling the
/// pushGLStates/popGLStates functions.
///
/// \see sf::RenderWindow, sf::RenderTexture, sf::View
///
////////////////////////////////////////////////////////////

View file

@ -1,280 +1,280 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RENDERTEXTURE_HPP
#define SFML_RENDERTEXTURE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
namespace sf
{
namespace priv
{
class RenderTextureImpl;
}
////////////////////////////////////////////////////////////
/// \brief Target for off-screen 2D rendering into a texture
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RenderTexture : public RenderTarget
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Constructs an empty, invalid render-texture. You must
/// call create to have a valid render-texture.
///
/// \see create
///
////////////////////////////////////////////////////////////
RenderTexture();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~RenderTexture();
////////////////////////////////////////////////////////////
/// \brief Create the render-texture
///
/// Before calling this function, the render-texture is in
/// an invalid state, thus it is mandatory to call it before
/// doing anything with the render-texture.
/// The last parameter, \a depthBuffer, is useful if you want
/// to use the render-texture for 3D OpenGL rendering that requires
/// a depth-buffer. Otherwise it is unnecessary, and you should
/// leave this parameter to false (which is its default value).
///
/// \param width Width of the render-texture
/// \param height Height of the render-texture
/// \param depthBuffer Do you want this render-texture to have a depth buffer?
///
/// \return True if creation has been successful
///
////////////////////////////////////////////////////////////
bool create(unsigned int width, unsigned int height, bool depthBuffer = false);
////////////////////////////////////////////////////////////
/// \brief Enable or disable texture smoothing
///
/// This function is similar to Texture::setSmooth.
/// This parameter is disabled by default.
///
/// \param smooth True to enable smoothing, false to disable it
///
/// \see isSmooth
///
////////////////////////////////////////////////////////////
void setSmooth(bool smooth);
////////////////////////////////////////////////////////////
/// \brief Tell whether the smooth filtering is enabled or not
///
/// \return True if texture smoothing is enabled
///
/// \see setSmooth
///
////////////////////////////////////////////////////////////
bool isSmooth() const;
////////////////////////////////////////////////////////////
/// \brief Enable or disable texture repeating
///
/// This function is similar to Texture::setRepeated.
/// This parameter is disabled by default.
///
/// \param repeated True to enable repeating, false to disable it
///
/// \see isRepeated
///
////////////////////////////////////////////////////////////
void setRepeated(bool repeated);
////////////////////////////////////////////////////////////
/// \brief Tell whether the texture is repeated or not
///
/// \return True if texture is repeated
///
/// \see setRepeated
///
////////////////////////////////////////////////////////////
bool isRepeated() const;
////////////////////////////////////////////////////////////
/// \brief Activate of deactivate the render-texture for rendering
///
/// This function makes the render-texture's context current for
/// future OpenGL rendering operations (so you shouldn't care
/// about it if you're not doing direct OpenGL stuff).
/// Only one context can be current in a thread, so if you
/// want to draw OpenGL geometry to another render target
/// (like a RenderWindow) don't forget to activate it again.
///
/// \param active True to activate, false to deactivate
///
/// \return True if operation was successful, false otherwise
///
////////////////////////////////////////////////////////////
bool setActive(bool active = true);
////////////////////////////////////////////////////////////
/// \brief Update the contents of the target texture
///
/// This function updates the target texture with what
/// has been drawn so far. Like for windows, calling this
/// function is mandatory at the end of rendering. Not calling
/// it may leave the texture in an undefined state.
///
////////////////////////////////////////////////////////////
void display();
////////////////////////////////////////////////////////////
/// \brief Return the size of the rendering region of the texture
///
/// The returned value is the size that you passed to
/// the create function.
///
/// \return Size in pixels
///
////////////////////////////////////////////////////////////
virtual Vector2u getSize() const;
////////////////////////////////////////////////////////////
/// \brief Get a read-only reference to the target texture
///
/// After drawing to the render-texture and calling Display,
/// you can retrieve the updated texture using this function,
/// and draw it using a sprite (for example).
/// The internal sf::Texture of a render-texture is always the
/// same instance, so that it is possible to call this function
/// once and keep a reference to the texture even after it is
/// modified.
///
/// \return Const reference to the texture
///
////////////////////////////////////////////////////////////
const Texture& getTexture() const;
private :
////////////////////////////////////////////////////////////
/// \brief Activate the target for rendering
///
/// This function is called by the base class
/// everytime it's going to use OpenGL calls.
///
/// \param active True to make the target active, false to deactivate it
///
/// \return True if the function succeeded
///
////////////////////////////////////////////////////////////
virtual bool activate(bool active);
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
priv::RenderTextureImpl* m_impl; ///< Platform/hardware specific implementation
Texture m_texture; ///< Target texture to draw on
};
} // namespace sf
#endif // SFML_RENDERTEXTURE_HPP
////////////////////////////////////////////////////////////
/// \class sf::RenderTexture
/// \ingroup graphics
///
/// sf::RenderTexture is the little brother of sf::RenderWindow.
/// It implements the same 2D drawing and OpenGL-related functions
/// (see their base class sf::RenderTarget for more details),
/// the difference is that the result is stored in an off-screen
/// texture rather than being show in a window.
///
/// Rendering to a texture can be useful in a variety of situations:
/// \li precomputing a complex static texture (like a level's background from multiple tiles)
/// \li applying post-effects to the whole scene with shaders
/// \li creating a sprite from a 3D object rendered with OpenGL
/// \li etc.
///
/// Usage example:
///
/// \code
/// // Create a new render-window
/// sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
///
/// // Create a new render-texture
/// sf::RenderTexture texture;
/// if (!texture.create(500, 500))
/// return -1;
///
/// // The main loop
/// while (window.isOpen())
/// {
/// // Event processing
/// // ...
///
/// // Clear the whole texture with red color
/// texture.clear(sf::Color::Red);
///
/// // Draw stuff to the texture
/// texture.draw(sprite); // sprite is a sf::Sprite
/// texture.draw(shape); // shape is a sf::Shape
/// texture.draw(text); // text is a sf::Text
///
/// // We're done drawing to the texture
/// texture.display();
///
/// // Now we start rendering to the window, clear it first
/// window.clear();
///
/// // Draw the texture
/// sf::Sprite sprite(texture.getTexture());
/// window.draw(sprite);
///
/// // End the current frame and display its contents on screen
/// window.display();
/// }
/// \endcode
///
/// Like sf::RenderWindow, sf::RenderTexture is still able to render direct
/// OpenGL stuff. It is even possible to mix together OpenGL calls
/// and regular SFML drawing commands. If you need a depth buffer for
/// 3D rendering, don't forget to request it when calling RenderTexture::create.
///
/// \see sf::RenderTarget, sf::RenderWindow, sf::View, sf::Texture
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RENDERTEXTURE_HPP
#define SFML_RENDERTEXTURE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
namespace sf
{
namespace priv
{
class RenderTextureImpl;
}
////////////////////////////////////////////////////////////
/// \brief Target for off-screen 2D rendering into a texture
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RenderTexture : public RenderTarget
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Constructs an empty, invalid render-texture. You must
/// call create to have a valid render-texture.
///
/// \see create
///
////////////////////////////////////////////////////////////
RenderTexture();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~RenderTexture();
////////////////////////////////////////////////////////////
/// \brief Create the render-texture
///
/// Before calling this function, the render-texture is in
/// an invalid state, thus it is mandatory to call it before
/// doing anything with the render-texture.
/// The last parameter, \a depthBuffer, is useful if you want
/// to use the render-texture for 3D OpenGL rendering that requires
/// a depth-buffer. Otherwise it is unnecessary, and you should
/// leave this parameter to false (which is its default value).
///
/// \param width Width of the render-texture
/// \param height Height of the render-texture
/// \param depthBuffer Do you want this render-texture to have a depth buffer?
///
/// \return True if creation has been successful
///
////////////////////////////////////////////////////////////
bool create(unsigned int width, unsigned int height, bool depthBuffer = false);
////////////////////////////////////////////////////////////
/// \brief Enable or disable texture smoothing
///
/// This function is similar to Texture::setSmooth.
/// This parameter is disabled by default.
///
/// \param smooth True to enable smoothing, false to disable it
///
/// \see isSmooth
///
////////////////////////////////////////////////////////////
void setSmooth(bool smooth);
////////////////////////////////////////////////////////////
/// \brief Tell whether the smooth filtering is enabled or not
///
/// \return True if texture smoothing is enabled
///
/// \see setSmooth
///
////////////////////////////////////////////////////////////
bool isSmooth() const;
////////////////////////////////////////////////////////////
/// \brief Enable or disable texture repeating
///
/// This function is similar to Texture::setRepeated.
/// This parameter is disabled by default.
///
/// \param repeated True to enable repeating, false to disable it
///
/// \see isRepeated
///
////////////////////////////////////////////////////////////
void setRepeated(bool repeated);
////////////////////////////////////////////////////////////
/// \brief Tell whether the texture is repeated or not
///
/// \return True if texture is repeated
///
/// \see setRepeated
///
////////////////////////////////////////////////////////////
bool isRepeated() const;
////////////////////////////////////////////////////////////
/// \brief Activate of deactivate the render-texture for rendering
///
/// This function makes the render-texture's context current for
/// future OpenGL rendering operations (so you shouldn't care
/// about it if you're not doing direct OpenGL stuff).
/// Only one context can be current in a thread, so if you
/// want to draw OpenGL geometry to another render target
/// (like a RenderWindow) don't forget to activate it again.
///
/// \param active True to activate, false to deactivate
///
/// \return True if operation was successful, false otherwise
///
////////////////////////////////////////////////////////////
bool setActive(bool active = true);
////////////////////////////////////////////////////////////
/// \brief Update the contents of the target texture
///
/// This function updates the target texture with what
/// has been drawn so far. Like for windows, calling this
/// function is mandatory at the end of rendering. Not calling
/// it may leave the texture in an undefined state.
///
////////////////////////////////////////////////////////////
void display();
////////////////////////////////////////////////////////////
/// \brief Return the size of the rendering region of the texture
///
/// The returned value is the size that you passed to
/// the create function.
///
/// \return Size in pixels
///
////////////////////////////////////////////////////////////
virtual Vector2u getSize() const;
////////////////////////////////////////////////////////////
/// \brief Get a read-only reference to the target texture
///
/// After drawing to the render-texture and calling Display,
/// you can retrieve the updated texture using this function,
/// and draw it using a sprite (for example).
/// The internal sf::Texture of a render-texture is always the
/// same instance, so that it is possible to call this function
/// once and keep a reference to the texture even after it is
/// modified.
///
/// \return Const reference to the texture
///
////////////////////////////////////////////////////////////
const Texture& getTexture() const;
private:
////////////////////////////////////////////////////////////
/// \brief Activate the target for rendering
///
/// This function is called by the base class
/// everytime it's going to use OpenGL calls.
///
/// \param active True to make the target active, false to deactivate it
///
/// \return True if the function succeeded
///
////////////////////////////////////////////////////////////
virtual bool activate(bool active);
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
priv::RenderTextureImpl* m_impl; ///< Platform/hardware specific implementation
Texture m_texture; ///< Target texture to draw on
};
} // namespace sf
#endif // SFML_RENDERTEXTURE_HPP
////////////////////////////////////////////////////////////
/// \class sf::RenderTexture
/// \ingroup graphics
///
/// sf::RenderTexture is the little brother of sf::RenderWindow.
/// It implements the same 2D drawing and OpenGL-related functions
/// (see their base class sf::RenderTarget for more details),
/// the difference is that the result is stored in an off-screen
/// texture rather than being show in a window.
///
/// Rendering to a texture can be useful in a variety of situations:
/// \li precomputing a complex static texture (like a level's background from multiple tiles)
/// \li applying post-effects to the whole scene with shaders
/// \li creating a sprite from a 3D object rendered with OpenGL
/// \li etc.
///
/// Usage example:
///
/// \code
/// // Create a new render-window
/// sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
///
/// // Create a new render-texture
/// sf::RenderTexture texture;
/// if (!texture.create(500, 500))
/// return -1;
///
/// // The main loop
/// while (window.isOpen())
/// {
/// // Event processing
/// // ...
///
/// // Clear the whole texture with red color
/// texture.clear(sf::Color::Red);
///
/// // Draw stuff to the texture
/// texture.draw(sprite); // sprite is a sf::Sprite
/// texture.draw(shape); // shape is a sf::Shape
/// texture.draw(text); // text is a sf::Text
///
/// // We're done drawing to the texture
/// texture.display();
///
/// // Now we start rendering to the window, clear it first
/// window.clear();
///
/// // Draw the texture
/// sf::Sprite sprite(texture.getTexture());
/// window.draw(sprite);
///
/// // End the current frame and display its contents on screen
/// window.display();
/// }
/// \endcode
///
/// Like sf::RenderWindow, sf::RenderTexture is still able to render direct
/// OpenGL stuff. It is even possible to mix together OpenGL calls
/// and regular SFML drawing commands. If you need a depth buffer for
/// 3D rendering, don't forget to request it when calling RenderTexture::create.
///
/// \see sf::RenderTarget, sf::RenderWindow, sf::View, sf::Texture
///
////////////////////////////////////////////////////////////

View file

@ -1,267 +1,267 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RENDERWINDOW_HPP
#define SFML_RENDERWINDOW_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Image.hpp>
#include <SFML/Window/Window.hpp>
#include <string>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Window that can serve as a target for 2D drawing
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RenderWindow : public Window, public RenderTarget
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor doesn't actually create the window,
/// use the other constructors or call create() to do so.
///
////////////////////////////////////////////////////////////
RenderWindow();
////////////////////////////////////////////////////////////
/// \brief Construct a new window
///
/// This constructor creates the window with the size and pixel
/// depth defined in \a mode. An optional style can be passed to
/// customize the look and behaviour of the window (borders,
/// title bar, resizable, closable, ...).
///
/// The fourth parameter is an optional structure specifying
/// advanced OpenGL context settings such as antialiasing,
/// depth-buffer bits, etc. You shouldn't care about these
/// parameters for a regular usage of the graphics module.
///
/// \param mode Video mode to use (defines the width, height and depth of the rendering area of the window)
/// \param title Title of the window
/// \param style %Window style, a bitwise OR combination of sf::Style enumerators
/// \param settings Additional settings for the underlying OpenGL context
///
////////////////////////////////////////////////////////////
RenderWindow(VideoMode mode, const String& title, Uint32 style = Style::Default, const ContextSettings& settings = ContextSettings());
////////////////////////////////////////////////////////////
/// \brief Construct the window from an existing control
///
/// Use this constructor if you want to create an SFML
/// rendering area into an already existing control.
///
/// The second parameter is an optional structure specifying
/// advanced OpenGL context settings such as antialiasing,
/// depth-buffer bits, etc. You shouldn't care about these
/// parameters for a regular usage of the graphics module.
///
/// \param handle Platform-specific handle of the control (\a HWND on
/// Windows, \a %Window on Linux/FreeBSD, \a NSWindow on OS X)
/// \param settings Additional settings for the underlying OpenGL context
///
////////////////////////////////////////////////////////////
explicit RenderWindow(WindowHandle handle, const ContextSettings& settings = ContextSettings());
////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// Closes the window and frees all the resources attached to it.
///
////////////////////////////////////////////////////////////
virtual ~RenderWindow();
////////////////////////////////////////////////////////////
/// \brief Get the size of the rendering region of the window
///
/// The size doesn't include the titlebar and borders
/// of the window.
///
/// \return Size in pixels
///
////////////////////////////////////////////////////////////
virtual Vector2u getSize() const;
////////////////////////////////////////////////////////////
/// \brief Copy the current contents of the window to an image
///
/// This is a slow operation, whose main purpose is to make
/// screenshots of the application. If you want to update an
/// image with the contents of the window and then use it for
/// drawing, you should rather use a sf::Texture and its
/// update(Window&) function.
/// You can also draw things directly to a texture with the
/// sf::RenderTexture class.
///
/// \return Image containing the captured contents
///
////////////////////////////////////////////////////////////
Image capture() const;
protected:
////////////////////////////////////////////////////////////
/// \brief Function called after the window has been created
///
/// This function is called so that derived classes can
/// perform their own specific initialization as soon as
/// the window is created.
///
////////////////////////////////////////////////////////////
virtual void onCreate();
////////////////////////////////////////////////////////////
/// \brief Function called after the window has been resized
///
/// This function is called so that derived classes can
/// perform custom actions when the size of the window changes.
///
////////////////////////////////////////////////////////////
virtual void onResize();
private :
////////////////////////////////////////////////////////////
/// \brief Activate the target for rendering
///
/// \param active True to make the target active, false to deactivate it
///
/// \return True if the function succeeded
///
////////////////////////////////////////////////////////////
virtual bool activate(bool active);
};
} // namespace sf
#endif // SFML_RENDERWINDOW_HPP
////////////////////////////////////////////////////////////
/// \class sf::RenderWindow
/// \ingroup graphics
///
/// sf::RenderWindow is the main class of the Graphics module.
/// It defines an OS window that can be painted using the other
/// classes of the graphics module.
///
/// sf::RenderWindow is derived from sf::Window, thus it inherits
/// all its features: events, window management, OpenGL rendering,
/// etc. See the documentation of sf::Window for a more complete
/// description of all these features, as well as code examples.
///
/// On top of that, sf::RenderWindow adds more features related to
/// 2D drawing with the graphics module (see its base class
/// sf::RenderTarget for more details).
/// Here is a typical rendering and event loop with a sf::RenderWindow:
///
/// \code
/// // Declare and create a new render-window
/// sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
///
/// // Limit the framerate to 60 frames per second (this step is optional)
/// window.setFramerateLimit(60);
///
/// // The main loop - ends as soon as the window is closed
/// while (window.isOpen())
/// {
/// // Event processing
/// sf::Event event;
/// while (window.pollEvent(event))
/// {
/// // Request for closing the window
/// if (event.type == sf::Event::Closed)
/// window.close();
/// }
///
/// // Clear the whole window before rendering a new frame
/// window.clear();
///
/// // Draw some graphical entities
/// window.draw(sprite);
/// window.draw(circle);
/// window.draw(text);
///
/// // End the current frame and display its contents on screen
/// window.display();
/// }
/// \endcode
///
/// Like sf::Window, sf::RenderWindow is still able to render direct
/// OpenGL stuff. It is even possible to mix together OpenGL calls
/// and regular SFML drawing commands.
///
/// \code
/// // Create the render window
/// sf::RenderWindow window(sf::VideoMode(800, 600), "SFML OpenGL");
///
/// // Create a sprite and a text to display
/// sf::Sprite sprite;
/// sf::Text text;
/// ...
///
/// // Perform OpenGL initializations
/// glMatrixMode(GL_PROJECTION);
/// ...
///
/// // Start the rendering loop
/// while (window.isOpen())
/// {
/// // Process events
/// ...
///
/// // Draw a background sprite
/// window.pushGLStates();
/// window.draw(sprite);
/// window.popGLStates();
///
/// // Draw a 3D object using OpenGL
/// glBegin(GL_QUADS);
/// glVertex3f(...);
/// ...
/// glEnd();
///
/// // Draw text on top of the 3D object
/// window.pushGLStates();
/// window.draw(text);
/// window.popGLStates();
///
/// // Finally, display the rendered frame on screen
/// window.display();
/// }
/// \endcode
///
/// \see sf::Window, sf::RenderTarget, sf::RenderTexture, sf::View
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RENDERWINDOW_HPP
#define SFML_RENDERWINDOW_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Image.hpp>
#include <SFML/Window/Window.hpp>
#include <string>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Window that can serve as a target for 2D drawing
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RenderWindow : public Window, public RenderTarget
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor doesn't actually create the window,
/// use the other constructors or call create() to do so.
///
////////////////////////////////////////////////////////////
RenderWindow();
////////////////////////////////////////////////////////////
/// \brief Construct a new window
///
/// This constructor creates the window with the size and pixel
/// depth defined in \a mode. An optional style can be passed to
/// customize the look and behaviour of the window (borders,
/// title bar, resizable, closable, ...).
///
/// The fourth parameter is an optional structure specifying
/// advanced OpenGL context settings such as antialiasing,
/// depth-buffer bits, etc. You shouldn't care about these
/// parameters for a regular usage of the graphics module.
///
/// \param mode Video mode to use (defines the width, height and depth of the rendering area of the window)
/// \param title Title of the window
/// \param style %Window style, a bitwise OR combination of sf::Style enumerators
/// \param settings Additional settings for the underlying OpenGL context
///
////////////////////////////////////////////////////////////
RenderWindow(VideoMode mode, const String& title, Uint32 style = Style::Default, const ContextSettings& settings = ContextSettings());
////////////////////////////////////////////////////////////
/// \brief Construct the window from an existing control
///
/// Use this constructor if you want to create an SFML
/// rendering area into an already existing control.
///
/// The second parameter is an optional structure specifying
/// advanced OpenGL context settings such as antialiasing,
/// depth-buffer bits, etc. You shouldn't care about these
/// parameters for a regular usage of the graphics module.
///
/// \param handle Platform-specific handle of the control (\a HWND on
/// Windows, \a %Window on Linux/FreeBSD, \a NSWindow on OS X)
/// \param settings Additional settings for the underlying OpenGL context
///
////////////////////////////////////////////////////////////
explicit RenderWindow(WindowHandle handle, const ContextSettings& settings = ContextSettings());
////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// Closes the window and frees all the resources attached to it.
///
////////////////////////////////////////////////////////////
virtual ~RenderWindow();
////////////////////////////////////////////////////////////
/// \brief Get the size of the rendering region of the window
///
/// The size doesn't include the titlebar and borders
/// of the window.
///
/// \return Size in pixels
///
////////////////////////////////////////////////////////////
virtual Vector2u getSize() const;
////////////////////////////////////////////////////////////
/// \brief Copy the current contents of the window to an image
///
/// This is a slow operation, whose main purpose is to make
/// screenshots of the application. If you want to update an
/// image with the contents of the window and then use it for
/// drawing, you should rather use a sf::Texture and its
/// update(Window&) function.
/// You can also draw things directly to a texture with the
/// sf::RenderTexture class.
///
/// \return Image containing the captured contents
///
////////////////////////////////////////////////////////////
Image capture() const;
protected:
////////////////////////////////////////////////////////////
/// \brief Function called after the window has been created
///
/// This function is called so that derived classes can
/// perform their own specific initialization as soon as
/// the window is created.
///
////////////////////////////////////////////////////////////
virtual void onCreate();
////////////////////////////////////////////////////////////
/// \brief Function called after the window has been resized
///
/// This function is called so that derived classes can
/// perform custom actions when the size of the window changes.
///
////////////////////////////////////////////////////////////
virtual void onResize();
private:
////////////////////////////////////////////////////////////
/// \brief Activate the target for rendering
///
/// \param active True to make the target active, false to deactivate it
///
/// \return True if the function succeeded
///
////////////////////////////////////////////////////////////
virtual bool activate(bool active);
};
} // namespace sf
#endif // SFML_RENDERWINDOW_HPP
////////////////////////////////////////////////////////////
/// \class sf::RenderWindow
/// \ingroup graphics
///
/// sf::RenderWindow is the main class of the Graphics module.
/// It defines an OS window that can be painted using the other
/// classes of the graphics module.
///
/// sf::RenderWindow is derived from sf::Window, thus it inherits
/// all its features: events, window management, OpenGL rendering,
/// etc. See the documentation of sf::Window for a more complete
/// description of all these features, as well as code examples.
///
/// On top of that, sf::RenderWindow adds more features related to
/// 2D drawing with the graphics module (see its base class
/// sf::RenderTarget for more details).
/// Here is a typical rendering and event loop with a sf::RenderWindow:
///
/// \code
/// // Declare and create a new render-window
/// sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
///
/// // Limit the framerate to 60 frames per second (this step is optional)
/// window.setFramerateLimit(60);
///
/// // The main loop - ends as soon as the window is closed
/// while (window.isOpen())
/// {
/// // Event processing
/// sf::Event event;
/// while (window.pollEvent(event))
/// {
/// // Request for closing the window
/// if (event.type == sf::Event::Closed)
/// window.close();
/// }
///
/// // Clear the whole window before rendering a new frame
/// window.clear();
///
/// // Draw some graphical entities
/// window.draw(sprite);
/// window.draw(circle);
/// window.draw(text);
///
/// // End the current frame and display its contents on screen
/// window.display();
/// }
/// \endcode
///
/// Like sf::Window, sf::RenderWindow is still able to render direct
/// OpenGL stuff. It is even possible to mix together OpenGL calls
/// and regular SFML drawing commands.
///
/// \code
/// // Create the render window
/// sf::RenderWindow window(sf::VideoMode(800, 600), "SFML OpenGL");
///
/// // Create a sprite and a text to display
/// sf::Sprite sprite;
/// sf::Text text;
/// ...
///
/// // Perform OpenGL initializations
/// glMatrixMode(GL_PROJECTION);
/// ...
///
/// // Start the rendering loop
/// while (window.isOpen())
/// {
/// // Process events
/// ...
///
/// // Draw a background sprite
/// window.pushGLStates();
/// window.draw(sprite);
/// window.popGLStates();
///
/// // Draw a 3D object using OpenGL
/// glBegin(GL_QUADS);
/// glVertex3f(...);
/// ...
/// glEnd();
///
/// // Draw text on top of the 3D object
/// window.pushGLStates();
/// window.draw(text);
/// window.popGLStates();
///
/// // Finally, display the rendered frame on screen
/// window.display();
/// }
/// \endcode
///
/// \see sf::Window, sf::RenderTarget, sf::RenderTexture, sf::View
///
////////////////////////////////////////////////////////////

File diff suppressed because it is too large Load diff

View file

@ -1,348 +1,348 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SHAPE_HPP
#define SFML_SHAPE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/System/Vector2.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Base class for textured shapes with outline
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Shape : public Drawable, public Transformable
{
public :
////////////////////////////////////////////////////////////
/// \brief Virtual destructor
///
////////////////////////////////////////////////////////////
virtual ~Shape();
////////////////////////////////////////////////////////////
/// \brief Change the source texture of the shape
///
/// The \a texture argument refers to a texture that must
/// exist as long as the shape uses it. Indeed, the shape
/// doesn't store its own copy of the texture, but rather keeps
/// a pointer to the one that you passed to this function.
/// If the source texture is destroyed and the shape tries to
/// use it, the behaviour is undefined.
/// \a texture can be NULL to disable texturing.
/// If \a resetRect is true, the TextureRect property of
/// the shape is automatically adjusted to the size of the new
/// texture. If it is false, the texture rect is left unchanged.
///
/// \param texture New texture
/// \param resetRect Should the texture rect be reset to the size of the new texture?
///
/// \see getTexture, setTextureRect
///
////////////////////////////////////////////////////////////
void setTexture(const Texture* texture, bool resetRect = false);
////////////////////////////////////////////////////////////
/// \brief Set the sub-rectangle of the texture that the shape will display
///
/// The texture rect is useful when you don't want to display
/// the whole texture, but rather a part of it.
/// By default, the texture rect covers the entire texture.
///
/// \param rect Rectangle defining the region of the texture to display
///
/// \see getTextureRect, setTexture
///
////////////////////////////////////////////////////////////
void setTextureRect(const IntRect& rect);
////////////////////////////////////////////////////////////
/// \brief Set the fill color of the shape
///
/// This color is modulated (multiplied) with the shape's
/// texture if any. It can be used to colorize the shape,
/// or change its global opacity.
/// You can use sf::Color::Transparent to make the inside of
/// the shape transparent, and have the outline alone.
/// By default, the shape's fill color is opaque white.
///
/// \param color New color of the shape
///
/// \see getFillColor, setOutlineColor
///
////////////////////////////////////////////////////////////
void setFillColor(const Color& color);
////////////////////////////////////////////////////////////
/// \brief Set the outline color of the shape
///
/// By default, the shape's outline color is opaque white.
///
/// \param color New outline color of the shape
///
/// \see getOutlineColor, setFillColor
///
////////////////////////////////////////////////////////////
void setOutlineColor(const Color& color);
////////////////////////////////////////////////////////////
/// \brief Set the thickness of the shape's outline
///
/// Note that negative values are allowed (so that the outline
/// expands towards the center of the shape), and using zero
/// disables the outline.
/// By default, the outline thickness is 0.
///
/// \param thickness New outline thickness
///
/// \see getOutlineThickness
///
////////////////////////////////////////////////////////////
void setOutlineThickness(float thickness);
////////////////////////////////////////////////////////////
/// \brief Get the source texture of the shape
///
/// If the shape has no source texture, a NULL pointer is returned.
/// The returned pointer is const, which means that you can't
/// modify the texture when you retrieve it with this function.
///
/// \return Pointer to the shape's texture
///
/// \see setTexture
///
////////////////////////////////////////////////////////////
const Texture* getTexture() const;
////////////////////////////////////////////////////////////
/// \brief Get the sub-rectangle of the texture displayed by the shape
///
/// \return Texture rectangle of the shape
///
/// \see setTextureRect
///
////////////////////////////////////////////////////////////
const IntRect& getTextureRect() const;
////////////////////////////////////////////////////////////
/// \brief Get the fill color of the shape
///
/// \return Fill color of the shape
///
/// \see setFillColor
///
////////////////////////////////////////////////////////////
const Color& getFillColor() const;
////////////////////////////////////////////////////////////
/// \brief Get the outline color of the shape
///
/// \return Outline color of the shape
///
/// \see setOutlineColor
///
////////////////////////////////////////////////////////////
const Color& getOutlineColor() const;
////////////////////////////////////////////////////////////
/// \brief Get the outline thickness of the shape
///
/// \return Outline thickness of the shape
///
/// \see setOutlineThickness
///
////////////////////////////////////////////////////////////
float getOutlineThickness() const;
////////////////////////////////////////////////////////////
/// \brief Get the total number of points of the shape
///
/// \return Number of points of the shape
///
/// \see getPoint
///
////////////////////////////////////////////////////////////
virtual unsigned int getPointCount() const = 0;
////////////////////////////////////////////////////////////
/// \brief Get a point of the shape
///
/// The returned point is in local coordinates, that is,
/// the shape's transforms (position, rotation, scale) are
/// not taken into account.
/// The result is undefined if \a index is out of the valid range.
///
/// \param index Index of the point to get, in range [0 .. getPointCount() - 1]
///
/// \return index-th point of the shape
///
/// \see getPointCount
///
////////////////////////////////////////////////////////////
virtual Vector2f getPoint(unsigned int index) const = 0;
////////////////////////////////////////////////////////////
/// \brief Get the local bounding rectangle of the entity
///
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
///
/// \return Local bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getLocalBounds() const;
////////////////////////////////////////////////////////////
/// \brief Get the global bounding rectangle of the entity
///
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
///
/// \return Global bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getGlobalBounds() const;
protected :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Shape();
////////////////////////////////////////////////////////////
/// \brief Recompute the internal geometry of the shape
///
/// This function must be called by the derived class everytime
/// the shape's points change (ie. the result of either
/// getPointCount or getPoint is different).
///
////////////////////////////////////////////////////////////
void update();
private :
////////////////////////////////////////////////////////////
/// \brief Draw the shape to a render target
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const;
////////////////////////////////////////////////////////////
/// \brief Update the fill vertices' color
///
////////////////////////////////////////////////////////////
void updateFillColors();
////////////////////////////////////////////////////////////
/// \brief Update the fill vertices' texture coordinates
///
////////////////////////////////////////////////////////////
void updateTexCoords();
////////////////////////////////////////////////////////////
/// \brief Update the outline vertices' position
///
////////////////////////////////////////////////////////////
void updateOutline();
////////////////////////////////////////////////////////////
/// \brief Update the outline vertices' color
///
////////////////////////////////////////////////////////////
void updateOutlineColors();
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
const Texture* m_texture; ///< Texture of the shape
IntRect m_textureRect; ///< Rectangle defining the area of the source texture to display
Color m_fillColor; ///< Fill color
Color m_outlineColor; ///< Outline color
float m_outlineThickness; ///< Thickness of the shape's outline
VertexArray m_vertices; ///< Vertex array containing the fill geometry
VertexArray m_outlineVertices; ///< Vertex array containing the outline geometry
FloatRect m_insideBounds; ///< Bounding rectangle of the inside (fill)
FloatRect m_bounds; ///< Bounding rectangle of the whole shape (outline + fill)
};
} // namespace sf
#endif // SFML_SHAPE_HPP
////////////////////////////////////////////////////////////
/// \class sf::Shape
/// \ingroup graphics
///
/// sf::Shape is a drawable class that allows to define and
/// display a custom convex shape on a render target.
/// It's only an abstract base, it needs to be specialized for
/// concrete types of shapes (circle, rectangle, convex polygon,
/// star, ...).
///
/// In addition to the attributes provided by the specialized
/// shape classes, a shape always has the following attributes:
/// \li a texture
/// \li a texture rectangle
/// \li a fill color
/// \li an outline color
/// \li an outline thickness
///
/// Each feature is optional, and can be disabled easily:
/// \li the texture can be null
/// \li the fill/outline colors can be sf::Color::Transparent
/// \li the outline thickness can be zero
///
/// You can write your own derived shape class, there are only
/// two virtual functions to override:
/// \li getPointCount must return the number of points of the shape
/// \li getPoint must return the points of the shape
///
/// \see sf::RectangleShape, sf::CircleShape, sf::ConvexShape, sf::Transformable
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SHAPE_HPP
#define SFML_SHAPE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/System/Vector2.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Base class for textured shapes with outline
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Shape : public Drawable, public Transformable
{
public:
////////////////////////////////////////////////////////////
/// \brief Virtual destructor
///
////////////////////////////////////////////////////////////
virtual ~Shape();
////////////////////////////////////////////////////////////
/// \brief Change the source texture of the shape
///
/// The \a texture argument refers to a texture that must
/// exist as long as the shape uses it. Indeed, the shape
/// doesn't store its own copy of the texture, but rather keeps
/// a pointer to the one that you passed to this function.
/// If the source texture is destroyed and the shape tries to
/// use it, the behaviour is undefined.
/// \a texture can be NULL to disable texturing.
/// If \a resetRect is true, the TextureRect property of
/// the shape is automatically adjusted to the size of the new
/// texture. If it is false, the texture rect is left unchanged.
///
/// \param texture New texture
/// \param resetRect Should the texture rect be reset to the size of the new texture?
///
/// \see getTexture, setTextureRect
///
////////////////////////////////////////////////////////////
void setTexture(const Texture* texture, bool resetRect = false);
////////////////////////////////////////////////////////////
/// \brief Set the sub-rectangle of the texture that the shape will display
///
/// The texture rect is useful when you don't want to display
/// the whole texture, but rather a part of it.
/// By default, the texture rect covers the entire texture.
///
/// \param rect Rectangle defining the region of the texture to display
///
/// \see getTextureRect, setTexture
///
////////////////////////////////////////////////////////////
void setTextureRect(const IntRect& rect);
////////////////////////////////////////////////////////////
/// \brief Set the fill color of the shape
///
/// This color is modulated (multiplied) with the shape's
/// texture if any. It can be used to colorize the shape,
/// or change its global opacity.
/// You can use sf::Color::Transparent to make the inside of
/// the shape transparent, and have the outline alone.
/// By default, the shape's fill color is opaque white.
///
/// \param color New color of the shape
///
/// \see getFillColor, setOutlineColor
///
////////////////////////////////////////////////////////////
void setFillColor(const Color& color);
////////////////////////////////////////////////////////////
/// \brief Set the outline color of the shape
///
/// By default, the shape's outline color is opaque white.
///
/// \param color New outline color of the shape
///
/// \see getOutlineColor, setFillColor
///
////////////////////////////////////////////////////////////
void setOutlineColor(const Color& color);
////////////////////////////////////////////////////////////
/// \brief Set the thickness of the shape's outline
///
/// Note that negative values are allowed (so that the outline
/// expands towards the center of the shape), and using zero
/// disables the outline.
/// By default, the outline thickness is 0.
///
/// \param thickness New outline thickness
///
/// \see getOutlineThickness
///
////////////////////////////////////////////////////////////
void setOutlineThickness(float thickness);
////////////////////////////////////////////////////////////
/// \brief Get the source texture of the shape
///
/// If the shape has no source texture, a NULL pointer is returned.
/// The returned pointer is const, which means that you can't
/// modify the texture when you retrieve it with this function.
///
/// \return Pointer to the shape's texture
///
/// \see setTexture
///
////////////////////////////////////////////////////////////
const Texture* getTexture() const;
////////////////////////////////////////////////////////////
/// \brief Get the sub-rectangle of the texture displayed by the shape
///
/// \return Texture rectangle of the shape
///
/// \see setTextureRect
///
////////////////////////////////////////////////////////////
const IntRect& getTextureRect() const;
////////////////////////////////////////////////////////////
/// \brief Get the fill color of the shape
///
/// \return Fill color of the shape
///
/// \see setFillColor
///
////////////////////////////////////////////////////////////
const Color& getFillColor() const;
////////////////////////////////////////////////////////////
/// \brief Get the outline color of the shape
///
/// \return Outline color of the shape
///
/// \see setOutlineColor
///
////////////////////////////////////////////////////////////
const Color& getOutlineColor() const;
////////////////////////////////////////////////////////////
/// \brief Get the outline thickness of the shape
///
/// \return Outline thickness of the shape
///
/// \see setOutlineThickness
///
////////////////////////////////////////////////////////////
float getOutlineThickness() const;
////////////////////////////////////////////////////////////
/// \brief Get the total number of points of the shape
///
/// \return Number of points of the shape
///
/// \see getPoint
///
////////////////////////////////////////////////////////////
virtual unsigned int getPointCount() const = 0;
////////////////////////////////////////////////////////////
/// \brief Get a point of the shape
///
/// The returned point is in local coordinates, that is,
/// the shape's transforms (position, rotation, scale) are
/// not taken into account.
/// The result is undefined if \a index is out of the valid range.
///
/// \param index Index of the point to get, in range [0 .. getPointCount() - 1]
///
/// \return index-th point of the shape
///
/// \see getPointCount
///
////////////////////////////////////////////////////////////
virtual Vector2f getPoint(unsigned int index) const = 0;
////////////////////////////////////////////////////////////
/// \brief Get the local bounding rectangle of the entity
///
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
///
/// \return Local bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getLocalBounds() const;
////////////////////////////////////////////////////////////
/// \brief Get the global bounding rectangle of the entity
///
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
///
/// \return Global bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getGlobalBounds() const;
protected:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Shape();
////////////////////////////////////////////////////////////
/// \brief Recompute the internal geometry of the shape
///
/// This function must be called by the derived class everytime
/// the shape's points change (ie. the result of either
/// getPointCount or getPoint is different).
///
////////////////////////////////////////////////////////////
void update();
private:
////////////////////////////////////////////////////////////
/// \brief Draw the shape to a render target
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const;
////////////////////////////////////////////////////////////
/// \brief Update the fill vertices' color
///
////////////////////////////////////////////////////////////
void updateFillColors();
////////////////////////////////////////////////////////////
/// \brief Update the fill vertices' texture coordinates
///
////////////////////////////////////////////////////////////
void updateTexCoords();
////////////////////////////////////////////////////////////
/// \brief Update the outline vertices' position
///
////////////////////////////////////////////////////////////
void updateOutline();
////////////////////////////////////////////////////////////
/// \brief Update the outline vertices' color
///
////////////////////////////////////////////////////////////
void updateOutlineColors();
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
const Texture* m_texture; ///< Texture of the shape
IntRect m_textureRect; ///< Rectangle defining the area of the source texture to display
Color m_fillColor; ///< Fill color
Color m_outlineColor; ///< Outline color
float m_outlineThickness; ///< Thickness of the shape's outline
VertexArray m_vertices; ///< Vertex array containing the fill geometry
VertexArray m_outlineVertices; ///< Vertex array containing the outline geometry
FloatRect m_insideBounds; ///< Bounding rectangle of the inside (fill)
FloatRect m_bounds; ///< Bounding rectangle of the whole shape (outline + fill)
};
} // namespace sf
#endif // SFML_SHAPE_HPP
////////////////////////////////////////////////////////////
/// \class sf::Shape
/// \ingroup graphics
///
/// sf::Shape is a drawable class that allows to define and
/// display a custom convex shape on a render target.
/// It's only an abstract base, it needs to be specialized for
/// concrete types of shapes (circle, rectangle, convex polygon,
/// star, ...).
///
/// In addition to the attributes provided by the specialized
/// shape classes, a shape always has the following attributes:
/// \li a texture
/// \li a texture rectangle
/// \li a fill color
/// \li an outline color
/// \li an outline thickness
///
/// Each feature is optional, and can be disabled easily:
/// \li the texture can be null
/// \li the fill/outline colors can be sf::Color::Transparent
/// \li the outline thickness can be zero
///
/// You can write your own derived shape class, there are only
/// two virtual functions to override:
/// \li getPointCount must return the number of points of the shape
/// \li getPoint must return the points of the shape
///
/// \see sf::RectangleShape, sf::CircleShape, sf::ConvexShape, sf::Transformable
///
////////////////////////////////////////////////////////////

View file

@ -1,279 +1,279 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SPRITE_HPP
#define SFML_SPRITE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/Rect.hpp>
namespace sf
{
class Texture;
////////////////////////////////////////////////////////////
/// \brief Drawable representation of a texture, with its
/// own transformations, color, etc.
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Sprite : public Drawable, public Transformable
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty sprite with no source texture.
///
////////////////////////////////////////////////////////////
Sprite();
////////////////////////////////////////////////////////////
/// \brief Construct the sprite from a source texture
///
/// \param texture Source texture
///
/// \see setTexture
///
////////////////////////////////////////////////////////////
explicit Sprite(const Texture& texture);
////////////////////////////////////////////////////////////
/// \brief Construct the sprite from a sub-rectangle of a source texture
///
/// \param texture Source texture
/// \param rectangle Sub-rectangle of the texture to assign to the sprite
///
/// \see setTexture, setTextureRect
///
////////////////////////////////////////////////////////////
Sprite(const Texture& texture, const IntRect& rectangle);
////////////////////////////////////////////////////////////
/// \brief Change the source texture of the sprite
///
/// The \a texture argument refers to a texture that must
/// exist as long as the sprite uses it. Indeed, the sprite
/// doesn't store its own copy of the texture, but rather keeps
/// a pointer to the one that you passed to this function.
/// If the source texture is destroyed and the sprite tries to
/// use it, the behaviour is undefined.
/// If \a resetRect is true, the TextureRect property of
/// the sprite is automatically adjusted to the size of the new
/// texture. If it is false, the texture rect is left unchanged.
///
/// \param texture New texture
/// \param resetRect Should the texture rect be reset to the size of the new texture?
///
/// \see getTexture, setTextureRect
///
////////////////////////////////////////////////////////////
void setTexture(const Texture& texture, bool resetRect = false);
////////////////////////////////////////////////////////////
/// \brief Set the sub-rectangle of the texture that the sprite will display
///
/// The texture rect is useful when you don't want to display
/// the whole texture, but rather a part of it.
/// By default, the texture rect covers the entire texture.
///
/// \param rectangle Rectangle defining the region of the texture to display
///
/// \see getTextureRect, setTexture
///
////////////////////////////////////////////////////////////
void setTextureRect(const IntRect& rectangle);
////////////////////////////////////////////////////////////
/// \brief Set the global color of the sprite
///
/// This color is modulated (multiplied) with the sprite's
/// texture. It can be used to colorize the sprite, or change
/// its global opacity.
/// By default, the sprite's color is opaque white.
///
/// \param color New color of the sprite
///
/// \see getColor
///
////////////////////////////////////////////////////////////
void setColor(const Color& color);
////////////////////////////////////////////////////////////
/// \brief Get the source texture of the sprite
///
/// If the sprite has no source texture, a NULL pointer is returned.
/// The returned pointer is const, which means that you can't
/// modify the texture when you retrieve it with this function.
///
/// \return Pointer to the sprite's texture
///
/// \see setTexture
///
////////////////////////////////////////////////////////////
const Texture* getTexture() const;
////////////////////////////////////////////////////////////
/// \brief Get the sub-rectangle of the texture displayed by the sprite
///
/// \return Texture rectangle of the sprite
///
/// \see setTextureRect
///
////////////////////////////////////////////////////////////
const IntRect& getTextureRect() const;
////////////////////////////////////////////////////////////
/// \brief Get the global color of the sprite
///
/// \return Global color of the sprite
///
/// \see setColor
///
////////////////////////////////////////////////////////////
const Color& getColor() const;
////////////////////////////////////////////////////////////
/// \brief Get the local bounding rectangle of the entity
///
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
///
/// \return Local bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getLocalBounds() const;
////////////////////////////////////////////////////////////
/// \brief Get the global bounding rectangle of the entity
///
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
///
/// \return Global bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getGlobalBounds() const;
private :
////////////////////////////////////////////////////////////
/// \brief Draw the sprite to a render target
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const;
////////////////////////////////////////////////////////////
/// \brief Update the vertices' positions
///
////////////////////////////////////////////////////////////
void updatePositions();
////////////////////////////////////////////////////////////
/// \brief Update the vertices' texture coordinates
///
////////////////////////////////////////////////////////////
void updateTexCoords();
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Vertex m_vertices[4]; ///< Vertices defining the sprite's geometry
const Texture* m_texture; ///< Texture of the sprite
IntRect m_textureRect; ///< Rectangle defining the area of the source texture to display
};
} // namespace sf
#endif // SFML_SPRITE_HPP
////////////////////////////////////////////////////////////
/// \class sf::Sprite
/// \ingroup graphics
///
/// sf::Sprite is a drawable class that allows to easily display
/// a texture (or a part of it) on a render target.
///
/// It inherits all the functions from sf::Transformable:
/// position, rotation, scale, origin. It also adds sprite-specific
/// properties such as the texture to use, the part of it to display,
/// and some convenience functions to change the overall color of the
/// sprite, or to get its bounding rectangle.
///
/// sf::Sprite works in combination with the sf::Texture class, which
/// loads and provides the pixel data of a given texture.
///
/// The separation of sf::Sprite and sf::Texture allows more flexibility
/// and better performances: indeed a sf::Texture is a heavy resource,
/// and any operation on it is slow (often too slow for real-time
/// applications). On the other side, a sf::Sprite is a lightweight
/// object which can use the pixel data of a sf::Texture and draw
/// it with its own transformation/color/blending attributes.
///
/// It is important to note that the sf::Sprite instance doesn't
/// copy the texture that it uses, it only keeps a reference to it.
/// Thus, a sf::Texture must not be destroyed while it is
/// used by a sf::Sprite (i.e. never write a function that
/// uses a local sf::Texture instance for creating a sprite).
///
/// See also the note on coordinates and undistorted rendering in sf::Transformable.
///
/// Usage example:
/// \code
/// // Declare and load a texture
/// sf::Texture texture;
/// texture.loadFromFile("texture.png");
///
/// // Create a sprite
/// sf::Sprite sprite;
/// sprite.setTexture(texture);
/// sprite.setTextureRect(sf::IntRect(10, 10, 50, 30));
/// sprite.setColor(sf::Color(255, 255, 255, 200));
/// sprite.setPosition(100, 25);
///
/// // Draw it
/// window.draw(sprite);
/// \endcode
///
/// \see sf::Texture, sf::Transformable
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SPRITE_HPP
#define SFML_SPRITE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/Rect.hpp>
namespace sf
{
class Texture;
////////////////////////////////////////////////////////////
/// \brief Drawable representation of a texture, with its
/// own transformations, color, etc.
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Sprite : public Drawable, public Transformable
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty sprite with no source texture.
///
////////////////////////////////////////////////////////////
Sprite();
////////////////////////////////////////////////////////////
/// \brief Construct the sprite from a source texture
///
/// \param texture Source texture
///
/// \see setTexture
///
////////////////////////////////////////////////////////////
explicit Sprite(const Texture& texture);
////////////////////////////////////////////////////////////
/// \brief Construct the sprite from a sub-rectangle of a source texture
///
/// \param texture Source texture
/// \param rectangle Sub-rectangle of the texture to assign to the sprite
///
/// \see setTexture, setTextureRect
///
////////////////////////////////////////////////////////////
Sprite(const Texture& texture, const IntRect& rectangle);
////////////////////////////////////////////////////////////
/// \brief Change the source texture of the sprite
///
/// The \a texture argument refers to a texture that must
/// exist as long as the sprite uses it. Indeed, the sprite
/// doesn't store its own copy of the texture, but rather keeps
/// a pointer to the one that you passed to this function.
/// If the source texture is destroyed and the sprite tries to
/// use it, the behaviour is undefined.
/// If \a resetRect is true, the TextureRect property of
/// the sprite is automatically adjusted to the size of the new
/// texture. If it is false, the texture rect is left unchanged.
///
/// \param texture New texture
/// \param resetRect Should the texture rect be reset to the size of the new texture?
///
/// \see getTexture, setTextureRect
///
////////////////////////////////////////////////////////////
void setTexture(const Texture& texture, bool resetRect = false);
////////////////////////////////////////////////////////////
/// \brief Set the sub-rectangle of the texture that the sprite will display
///
/// The texture rect is useful when you don't want to display
/// the whole texture, but rather a part of it.
/// By default, the texture rect covers the entire texture.
///
/// \param rectangle Rectangle defining the region of the texture to display
///
/// \see getTextureRect, setTexture
///
////////////////////////////////////////////////////////////
void setTextureRect(const IntRect& rectangle);
////////////////////////////////////////////////////////////
/// \brief Set the global color of the sprite
///
/// This color is modulated (multiplied) with the sprite's
/// texture. It can be used to colorize the sprite, or change
/// its global opacity.
/// By default, the sprite's color is opaque white.
///
/// \param color New color of the sprite
///
/// \see getColor
///
////////////////////////////////////////////////////////////
void setColor(const Color& color);
////////////////////////////////////////////////////////////
/// \brief Get the source texture of the sprite
///
/// If the sprite has no source texture, a NULL pointer is returned.
/// The returned pointer is const, which means that you can't
/// modify the texture when you retrieve it with this function.
///
/// \return Pointer to the sprite's texture
///
/// \see setTexture
///
////////////////////////////////////////////////////////////
const Texture* getTexture() const;
////////////////////////////////////////////////////////////
/// \brief Get the sub-rectangle of the texture displayed by the sprite
///
/// \return Texture rectangle of the sprite
///
/// \see setTextureRect
///
////////////////////////////////////////////////////////////
const IntRect& getTextureRect() const;
////////////////////////////////////////////////////////////
/// \brief Get the global color of the sprite
///
/// \return Global color of the sprite
///
/// \see setColor
///
////////////////////////////////////////////////////////////
const Color& getColor() const;
////////////////////////////////////////////////////////////
/// \brief Get the local bounding rectangle of the entity
///
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
///
/// \return Local bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getLocalBounds() const;
////////////////////////////////////////////////////////////
/// \brief Get the global bounding rectangle of the entity
///
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
///
/// \return Global bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getGlobalBounds() const;
private:
////////////////////////////////////////////////////////////
/// \brief Draw the sprite to a render target
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const;
////////////////////////////////////////////////////////////
/// \brief Update the vertices' positions
///
////////////////////////////////////////////////////////////
void updatePositions();
////////////////////////////////////////////////////////////
/// \brief Update the vertices' texture coordinates
///
////////////////////////////////////////////////////////////
void updateTexCoords();
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Vertex m_vertices[4]; ///< Vertices defining the sprite's geometry
const Texture* m_texture; ///< Texture of the sprite
IntRect m_textureRect; ///< Rectangle defining the area of the source texture to display
};
} // namespace sf
#endif // SFML_SPRITE_HPP
////////////////////////////////////////////////////////////
/// \class sf::Sprite
/// \ingroup graphics
///
/// sf::Sprite is a drawable class that allows to easily display
/// a texture (or a part of it) on a render target.
///
/// It inherits all the functions from sf::Transformable:
/// position, rotation, scale, origin. It also adds sprite-specific
/// properties such as the texture to use, the part of it to display,
/// and some convenience functions to change the overall color of the
/// sprite, or to get its bounding rectangle.
///
/// sf::Sprite works in combination with the sf::Texture class, which
/// loads and provides the pixel data of a given texture.
///
/// The separation of sf::Sprite and sf::Texture allows more flexibility
/// and better performances: indeed a sf::Texture is a heavy resource,
/// and any operation on it is slow (often too slow for real-time
/// applications). On the other side, a sf::Sprite is a lightweight
/// object which can use the pixel data of a sf::Texture and draw
/// it with its own transformation/color/blending attributes.
///
/// It is important to note that the sf::Sprite instance doesn't
/// copy the texture that it uses, it only keeps a reference to it.
/// Thus, a sf::Texture must not be destroyed while it is
/// used by a sf::Sprite (i.e. never write a function that
/// uses a local sf::Texture instance for creating a sprite).
///
/// See also the note on coordinates and undistorted rendering in sf::Transformable.
///
/// Usage example:
/// \code
/// // Declare and load a texture
/// sf::Texture texture;
/// texture.loadFromFile("texture.png");
///
/// // Create a sprite
/// sf::Sprite sprite;
/// sprite.setTexture(texture);
/// sprite.setTextureRect(sf::IntRect(10, 10, 50, 30));
/// sprite.setColor(sf::Color(255, 255, 255, 200));
/// sprite.setPosition(100, 25);
///
/// // Draw it
/// window.draw(sprite);
/// \endcode
///
/// \see sf::Texture, sf::Transformable
///
////////////////////////////////////////////////////////////

View file

@ -1,372 +1,372 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_TEXT_HPP
#define SFML_TEXT_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/System/String.hpp>
#include <string>
#include <vector>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Graphical text that can be drawn to a render target
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Text : public Drawable, public Transformable
{
public :
////////////////////////////////////////////////////////////
/// \brief Enumeration of the string drawing styles
///
////////////////////////////////////////////////////////////
enum Style
{
Regular = 0, ///< Regular characters, no style
Bold = 1 << 0, ///< Bold characters
Italic = 1 << 1, ///< Italic characters
Underlined = 1 << 2, ///< Underlined characters
StrikeThrough = 1 << 3 ///< Strike through characters
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty text.
///
////////////////////////////////////////////////////////////
Text();
////////////////////////////////////////////////////////////
/// \brief Construct the text from a string, font and size
///
/// Note that if the used font is a bitmap font, it is not
/// scalable, thus not all requested sizes will be available
/// to use. This needs to be taken into consideration when
/// setting the character size. If you need to display text
/// of a certain size, make sure the corresponding bitmap
/// font that supports that size is used.
///
/// \param string Text assigned to the string
/// \param font Font used to draw the string
/// \param characterSize Base size of characters, in pixels
///
////////////////////////////////////////////////////////////
Text(const String& string, const Font& font, unsigned int characterSize = 30);
////////////////////////////////////////////////////////////
/// \brief Set the text's string
///
/// The \a string argument is a sf::String, which can
/// automatically be constructed from standard string types.
/// So, the following calls are all valid:
/// \code
/// text.setString("hello");
/// text.setString(L"hello");
/// text.setString(std::string("hello"));
/// text.setString(std::wstring(L"hello"));
/// \endcode
/// A text's string is empty by default.
///
/// \param string New string
///
/// \see getString
///
////////////////////////////////////////////////////////////
void setString(const String& string);
////////////////////////////////////////////////////////////
/// \brief Set the text's font
///
/// The \a font argument refers to a font that must
/// exist as long as the text uses it. Indeed, the text
/// doesn't store its own copy of the font, but rather keeps
/// a pointer to the one that you passed to this function.
/// If the font is destroyed and the text tries to
/// use it, the behaviour is undefined.
///
/// \param font New font
///
/// \see getFont
///
////////////////////////////////////////////////////////////
void setFont(const Font& font);
////////////////////////////////////////////////////////////
/// \brief Set the character size
///
/// The default size is 30.
///
/// Note that if the used font is a bitmap font, it is not
/// scalable, thus not all requested sizes will be available
/// to use. This needs to be taken into consideration when
/// setting the character size. If you need to display text
/// of a certain size, make sure the corresponding bitmap
/// font that supports that size is used.
///
/// \param size New character size, in pixels
///
/// \see getCharacterSize
///
////////////////////////////////////////////////////////////
void setCharacterSize(unsigned int size);
////////////////////////////////////////////////////////////
/// \brief Set the text's style
///
/// You can pass a combination of one or more styles, for
/// example sf::Text::Bold | sf::Text::Italic.
/// The default style is sf::Text::Regular.
///
/// \param style New style
///
/// \see getStyle
///
////////////////////////////////////////////////////////////
void setStyle(Uint32 style);
////////////////////////////////////////////////////////////
/// \brief Set the global color of the text
///
/// By default, the text's color is opaque white.
///
/// \param color New color of the text
///
/// \see getColor
///
////////////////////////////////////////////////////////////
void setColor(const Color& color);
////////////////////////////////////////////////////////////
/// \brief Get the text's string
///
/// The returned string is a sf::String, which can automatically
/// be converted to standard string types. So, the following
/// lines of code are all valid:
/// \code
/// sf::String s1 = text.getString();
/// std::string s2 = text.getString();
/// std::wstring s3 = text.getString();
/// \endcode
///
/// \return Text's string
///
/// \see setString
///
////////////////////////////////////////////////////////////
const String& getString() const;
////////////////////////////////////////////////////////////
/// \brief Get the text's font
///
/// If the text has no font attached, a NULL pointer is returned.
/// The returned reference is const, which means that you
/// cannot modify the font when you get it from this function.
///
/// \return Pointer to the text's font
///
/// \see setFont
///
////////////////////////////////////////////////////////////
const Font* getFont() const;
////////////////////////////////////////////////////////////
/// \brief Get the character size
///
/// \return Size of the characters, in pixels
///
/// \see setCharacterSize
///
////////////////////////////////////////////////////////////
unsigned int getCharacterSize() const;
////////////////////////////////////////////////////////////
/// \brief Get the text's style
///
/// \return Text's style
///
/// \see setStyle
///
////////////////////////////////////////////////////////////
Uint32 getStyle() const;
////////////////////////////////////////////////////////////
/// \brief Get the global color of the text
///
/// \return Global color of the text
///
/// \see setColor
///
////////////////////////////////////////////////////////////
const Color& getColor() const;
////////////////////////////////////////////////////////////
/// \brief Return the position of the \a index-th character
///
/// This function computes the visual position of a character
/// from its index in the string. The returned position is
/// in global coordinates (translation, rotation, scale and
/// origin are applied).
/// If \a index is out of range, the position of the end of
/// the string is returned.
///
/// \param index Index of the character
///
/// \return Position of the character
///
////////////////////////////////////////////////////////////
Vector2f findCharacterPos(std::size_t index) const;
////////////////////////////////////////////////////////////
/// \brief Get the local bounding rectangle of the entity
///
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
///
/// \return Local bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getLocalBounds() const;
////////////////////////////////////////////////////////////
/// \brief Get the global bounding rectangle of the entity
///
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
///
/// \return Global bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getGlobalBounds() const;
private :
////////////////////////////////////////////////////////////
/// \brief Draw the text to a render target
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const;
////////////////////////////////////////////////////////////
/// \brief Make sure the text's geometry is updated
///
/// All the attributes related to rendering are cached, such
/// that the geometry is only updated when necessary.
///
////////////////////////////////////////////////////////////
void ensureGeometryUpdate() const;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
String m_string; ///< String to display
const Font* m_font; ///< Font used to display the string
unsigned int m_characterSize; ///< Base size of characters, in pixels
Uint32 m_style; ///< Text style (see Style enum)
Color m_color; ///< Text color
mutable VertexArray m_vertices; ///< Vertex array containing the text's geometry
mutable FloatRect m_bounds; ///< Bounding rectangle of the text (in local coordinates)
mutable bool m_geometryNeedUpdate; ///< Does the geometry need to be recomputed?
};
} // namespace sf
#endif // SFML_TEXT_HPP
////////////////////////////////////////////////////////////
/// \class sf::Text
/// \ingroup graphics
///
/// sf::Text is a drawable class that allows to easily display
/// some text with custom style and color on a render target.
///
/// It inherits all the functions from sf::Transformable:
/// position, rotation, scale, origin. It also adds text-specific
/// properties such as the font to use, the character size,
/// the font style (bold, italic, underlined, strike through), the
/// global color and the text to display of course.
/// It also provides convenience functions to calculate the
/// graphical size of the text, or to get the global position
/// of a given character.
///
/// sf::Text works in combination with the sf::Font class, which
/// loads and provides the glyphs (visual characters) of a given font.
///
/// The separation of sf::Font and sf::Text allows more flexibility
/// and better performances: indeed a sf::Font is a heavy resource,
/// and any operation on it is slow (often too slow for real-time
/// applications). On the other side, a sf::Text is a lightweight
/// object which can combine the glyphs data and metrics of a sf::Font
/// to display any text on a render target.
///
/// It is important to note that the sf::Text instance doesn't
/// copy the font that it uses, it only keeps a reference to it.
/// Thus, a sf::Font must not be destructed while it is
/// used by a sf::Text (i.e. never write a function that
/// uses a local sf::Font instance for creating a text).
///
/// See also the note on coordinates and undistorted rendering in sf::Transformable.
///
/// Usage example:
/// \code
/// // Declare and load a font
/// sf::Font font;
/// font.loadFromFile("arial.ttf");
///
/// // Create a text
/// sf::Text text("hello", font);
/// text.setCharacterSize(30);
/// text.setStyle(sf::Text::Bold);
/// text.setColor(sf::Color::Red);
///
/// // Draw it
/// window.draw(text);
/// \endcode
///
/// \see sf::Font, sf::Transformable
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_TEXT_HPP
#define SFML_TEXT_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/System/String.hpp>
#include <string>
#include <vector>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Graphical text that can be drawn to a render target
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Text : public Drawable, public Transformable
{
public:
////////////////////////////////////////////////////////////
/// \brief Enumeration of the string drawing styles
///
////////////////////////////////////////////////////////////
enum Style
{
Regular = 0, ///< Regular characters, no style
Bold = 1 << 0, ///< Bold characters
Italic = 1 << 1, ///< Italic characters
Underlined = 1 << 2, ///< Underlined characters
StrikeThrough = 1 << 3 ///< Strike through characters
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty text.
///
////////////////////////////////////////////////////////////
Text();
////////////////////////////////////////////////////////////
/// \brief Construct the text from a string, font and size
///
/// Note that if the used font is a bitmap font, it is not
/// scalable, thus not all requested sizes will be available
/// to use. This needs to be taken into consideration when
/// setting the character size. If you need to display text
/// of a certain size, make sure the corresponding bitmap
/// font that supports that size is used.
///
/// \param string Text assigned to the string
/// \param font Font used to draw the string
/// \param characterSize Base size of characters, in pixels
///
////////////////////////////////////////////////////////////
Text(const String& string, const Font& font, unsigned int characterSize = 30);
////////////////////////////////////////////////////////////
/// \brief Set the text's string
///
/// The \a string argument is a sf::String, which can
/// automatically be constructed from standard string types.
/// So, the following calls are all valid:
/// \code
/// text.setString("hello");
/// text.setString(L"hello");
/// text.setString(std::string("hello"));
/// text.setString(std::wstring(L"hello"));
/// \endcode
/// A text's string is empty by default.
///
/// \param string New string
///
/// \see getString
///
////////////////////////////////////////////////////////////
void setString(const String& string);
////////////////////////////////////////////////////////////
/// \brief Set the text's font
///
/// The \a font argument refers to a font that must
/// exist as long as the text uses it. Indeed, the text
/// doesn't store its own copy of the font, but rather keeps
/// a pointer to the one that you passed to this function.
/// If the font is destroyed and the text tries to
/// use it, the behaviour is undefined.
///
/// \param font New font
///
/// \see getFont
///
////////////////////////////////////////////////////////////
void setFont(const Font& font);
////////////////////////////////////////////////////////////
/// \brief Set the character size
///
/// The default size is 30.
///
/// Note that if the used font is a bitmap font, it is not
/// scalable, thus not all requested sizes will be available
/// to use. This needs to be taken into consideration when
/// setting the character size. If you need to display text
/// of a certain size, make sure the corresponding bitmap
/// font that supports that size is used.
///
/// \param size New character size, in pixels
///
/// \see getCharacterSize
///
////////////////////////////////////////////////////////////
void setCharacterSize(unsigned int size);
////////////////////////////////////////////////////////////
/// \brief Set the text's style
///
/// You can pass a combination of one or more styles, for
/// example sf::Text::Bold | sf::Text::Italic.
/// The default style is sf::Text::Regular.
///
/// \param style New style
///
/// \see getStyle
///
////////////////////////////////////////////////////////////
void setStyle(Uint32 style);
////////////////////////////////////////////////////////////
/// \brief Set the global color of the text
///
/// By default, the text's color is opaque white.
///
/// \param color New color of the text
///
/// \see getColor
///
////////////////////////////////////////////////////////////
void setColor(const Color& color);
////////////////////////////////////////////////////////////
/// \brief Get the text's string
///
/// The returned string is a sf::String, which can automatically
/// be converted to standard string types. So, the following
/// lines of code are all valid:
/// \code
/// sf::String s1 = text.getString();
/// std::string s2 = text.getString();
/// std::wstring s3 = text.getString();
/// \endcode
///
/// \return Text's string
///
/// \see setString
///
////////////////////////////////////////////////////////////
const String& getString() const;
////////////////////////////////////////////////////////////
/// \brief Get the text's font
///
/// If the text has no font attached, a NULL pointer is returned.
/// The returned reference is const, which means that you
/// cannot modify the font when you get it from this function.
///
/// \return Pointer to the text's font
///
/// \see setFont
///
////////////////////////////////////////////////////////////
const Font* getFont() const;
////////////////////////////////////////////////////////////
/// \brief Get the character size
///
/// \return Size of the characters, in pixels
///
/// \see setCharacterSize
///
////////////////////////////////////////////////////////////
unsigned int getCharacterSize() const;
////////////////////////////////////////////////////////////
/// \brief Get the text's style
///
/// \return Text's style
///
/// \see setStyle
///
////////////////////////////////////////////////////////////
Uint32 getStyle() const;
////////////////////////////////////////////////////////////
/// \brief Get the global color of the text
///
/// \return Global color of the text
///
/// \see setColor
///
////////////////////////////////////////////////////////////
const Color& getColor() const;
////////////////////////////////////////////////////////////
/// \brief Return the position of the \a index-th character
///
/// This function computes the visual position of a character
/// from its index in the string. The returned position is
/// in global coordinates (translation, rotation, scale and
/// origin are applied).
/// If \a index is out of range, the position of the end of
/// the string is returned.
///
/// \param index Index of the character
///
/// \return Position of the character
///
////////////////////////////////////////////////////////////
Vector2f findCharacterPos(std::size_t index) const;
////////////////////////////////////////////////////////////
/// \brief Get the local bounding rectangle of the entity
///
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
///
/// \return Local bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getLocalBounds() const;
////////////////////////////////////////////////////////////
/// \brief Get the global bounding rectangle of the entity
///
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
///
/// \return Global bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getGlobalBounds() const;
private:
////////////////////////////////////////////////////////////
/// \brief Draw the text to a render target
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const;
////////////////////////////////////////////////////////////
/// \brief Make sure the text's geometry is updated
///
/// All the attributes related to rendering are cached, such
/// that the geometry is only updated when necessary.
///
////////////////////////////////////////////////////////////
void ensureGeometryUpdate() const;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
String m_string; ///< String to display
const Font* m_font; ///< Font used to display the string
unsigned int m_characterSize; ///< Base size of characters, in pixels
Uint32 m_style; ///< Text style (see Style enum)
Color m_color; ///< Text color
mutable VertexArray m_vertices; ///< Vertex array containing the text's geometry
mutable FloatRect m_bounds; ///< Bounding rectangle of the text (in local coordinates)
mutable bool m_geometryNeedUpdate; ///< Does the geometry need to be recomputed?
};
} // namespace sf
#endif // SFML_TEXT_HPP
////////////////////////////////////////////////////////////
/// \class sf::Text
/// \ingroup graphics
///
/// sf::Text is a drawable class that allows to easily display
/// some text with custom style and color on a render target.
///
/// It inherits all the functions from sf::Transformable:
/// position, rotation, scale, origin. It also adds text-specific
/// properties such as the font to use, the character size,
/// the font style (bold, italic, underlined, strike through), the
/// global color and the text to display of course.
/// It also provides convenience functions to calculate the
/// graphical size of the text, or to get the global position
/// of a given character.
///
/// sf::Text works in combination with the sf::Font class, which
/// loads and provides the glyphs (visual characters) of a given font.
///
/// The separation of sf::Font and sf::Text allows more flexibility
/// and better performances: indeed a sf::Font is a heavy resource,
/// and any operation on it is slow (often too slow for real-time
/// applications). On the other side, a sf::Text is a lightweight
/// object which can combine the glyphs data and metrics of a sf::Font
/// to display any text on a render target.
///
/// It is important to note that the sf::Text instance doesn't
/// copy the font that it uses, it only keeps a reference to it.
/// Thus, a sf::Font must not be destructed while it is
/// used by a sf::Text (i.e. never write a function that
/// uses a local sf::Font instance for creating a text).
///
/// See also the note on coordinates and undistorted rendering in sf::Transformable.
///
/// Usage example:
/// \code
/// // Declare and load a font
/// sf::Font font;
/// font.loadFromFile("arial.ttf");
///
/// // Create a text
/// sf::Text text("hello", font);
/// text.setCharacterSize(30);
/// text.setStyle(sf::Text::Bold);
/// text.setColor(sf::Color::Red);
///
/// // Draw it
/// window.draw(text);
/// \endcode
///
/// \see sf::Font, sf::Transformable
///
////////////////////////////////////////////////////////////

View file

@ -46,7 +46,7 @@ class InputStream;
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Texture : GlResource
{
public :
public:
////////////////////////////////////////////////////////////
/// \brief Types of texture coordinates that can be used for rendering
@ -58,7 +58,7 @@ public :
Pixels ///< Texture coordinates in range [0 .. size]
};
public :
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
@ -468,7 +468,7 @@ public :
////////////////////////////////////////////////////////////
static unsigned int getMaximumSize();
private :
private:
friend class RenderTexture;
friend class RenderTarget;

View file

@ -41,7 +41,7 @@ namespace sf
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Transform
{
public :
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor

View file

@ -40,7 +40,7 @@ namespace sf
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Transformable
{
public :
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
@ -311,7 +311,7 @@ public :
////////////////////////////////////////////////////////////
const Transform& getInverseTransform() const;
private :
private:
////////////////////////////////////////////////////////////
// Member data
@ -396,7 +396,7 @@ private :
/// \code
/// class MyEntity
/// {
/// public :
/// public:
/// void SetPosition(const MyVector& v)
/// {
/// myTransform.setPosition(v.x(), v.y());
@ -407,7 +407,7 @@ private :
/// target.draw(..., myTransform.getTransform());
/// }
///
/// private :
/// private:
/// sf::Transformable myTransform;
/// };
/// \endcode

View file

@ -41,7 +41,7 @@ namespace sf
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Vertex
{
public :
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor

View file

@ -44,7 +44,7 @@ namespace sf
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API VertexArray : public Drawable
{
public :
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
@ -171,7 +171,7 @@ public :
////////////////////////////////////////////////////////////
FloatRect getBounds() const;
private :
private:
////////////////////////////////////////////////////////////
/// \brief Draw the vertex array to a render target

View file

@ -1,343 +1,343 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_VIEW_HPP
#define SFML_VIEW_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/Transform.hpp>
#include <SFML/System/Vector2.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief 2D camera that defines what region is shown on screen
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API View
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor creates a default view of (0, 0, 1000, 1000)
///
////////////////////////////////////////////////////////////
View();
////////////////////////////////////////////////////////////
/// \brief Construct the view from a rectangle
///
/// \param rectangle Rectangle defining the zone to display
///
////////////////////////////////////////////////////////////
explicit View(const FloatRect& rectangle);
////////////////////////////////////////////////////////////
/// \brief Construct the view from its center and size
///
/// \param center Center of the zone to display
/// \param size Size of zone to display
///
////////////////////////////////////////////////////////////
View(const Vector2f& center, const Vector2f& size);
////////////////////////////////////////////////////////////
/// \brief Set the center of the view
///
/// \param x X coordinate of the new center
/// \param y Y coordinate of the new center
///
/// \see setSize, getCenter
///
////////////////////////////////////////////////////////////
void setCenter(float x, float y);
////////////////////////////////////////////////////////////
/// \brief Set the center of the view
///
/// \param center New center
///
/// \see setSize, getCenter
///
////////////////////////////////////////////////////////////
void setCenter(const Vector2f& center);
////////////////////////////////////////////////////////////
/// \brief Set the size of the view
///
/// \param width New width of the view
/// \param height New height of the view
///
/// \see setCenter, getCenter
///
////////////////////////////////////////////////////////////
void setSize(float width, float height);
////////////////////////////////////////////////////////////
/// \brief Set the size of the view
///
/// \param size New size
///
/// \see setCenter, getCenter
///
////////////////////////////////////////////////////////////
void setSize(const Vector2f& size);
////////////////////////////////////////////////////////////
/// \brief Set the orientation of the view
///
/// The default rotation of a view is 0 degree.
///
/// \param angle New angle, in degrees
///
/// \see getRotation
///
////////////////////////////////////////////////////////////
void setRotation(float angle);
////////////////////////////////////////////////////////////
/// \brief Set the target viewport
///
/// The viewport is the rectangle into which the contents of the
/// view are displayed, expressed as a factor (between 0 and 1)
/// of the size of the RenderTarget to which the view is applied.
/// For example, a view which takes the left side of the target would
/// be defined with View.setViewport(sf::FloatRect(0, 0, 0.5, 1)).
/// By default, a view has a viewport which covers the entire target.
///
/// \param viewport New viewport rectangle
///
/// \see getViewport
///
////////////////////////////////////////////////////////////
void setViewport(const FloatRect& viewport);
////////////////////////////////////////////////////////////
/// \brief Reset the view to the given rectangle
///
/// Note that this function resets the rotation angle to 0.
///
/// \param rectangle Rectangle defining the zone to display
///
/// \see setCenter, setSize, setRotation
///
////////////////////////////////////////////////////////////
void reset(const FloatRect& rectangle);
////////////////////////////////////////////////////////////
/// \brief Get the center of the view
///
/// \return Center of the view
///
/// \see getSize, setCenter
///
////////////////////////////////////////////////////////////
const Vector2f& getCenter() const;
////////////////////////////////////////////////////////////
/// \brief Get the size of the view
///
/// \return Size of the view
///
/// \see getCenter, setSize
///
////////////////////////////////////////////////////////////
const Vector2f& getSize() const;
////////////////////////////////////////////////////////////
/// \brief Get the current orientation of the view
///
/// \return Rotation angle of the view, in degrees
///
/// \see setRotation
///
////////////////////////////////////////////////////////////
float getRotation() const;
////////////////////////////////////////////////////////////
/// \brief Get the target viewport rectangle of the view
///
/// \return Viewport rectangle, expressed as a factor of the target size
///
/// \see setViewport
///
////////////////////////////////////////////////////////////
const FloatRect& getViewport() const;
////////////////////////////////////////////////////////////
/// \brief Move the view relatively to its current position
///
/// \param offsetX X coordinate of the move offset
/// \param offsetY Y coordinate of the move offset
///
/// \see setCenter, rotate, zoom
///
////////////////////////////////////////////////////////////
void move(float offsetX, float offsetY);
////////////////////////////////////////////////////////////
/// \brief Move the view relatively to its current position
///
/// \param offset Move offset
///
/// \see setCenter, rotate, zoom
///
////////////////////////////////////////////////////////////
void move(const Vector2f& offset);
////////////////////////////////////////////////////////////
/// \brief Rotate the view relatively to its current orientation
///
/// \param angle Angle to rotate, in degrees
///
/// \see setRotation, move, zoom
///
////////////////////////////////////////////////////////////
void rotate(float angle);
////////////////////////////////////////////////////////////
/// \brief Resize the view rectangle relatively to its current size
///
/// Resizing the view simulates a zoom, as the zone displayed on
/// screen grows or shrinks.
/// \a factor is a multiplier:
/// \li 1 keeps the size unchanged
/// \li > 1 makes the view bigger (objects appear smaller)
/// \li < 1 makes the view smaller (objects appear bigger)
///
/// \param factor Zoom factor to apply
///
/// \see setSize, move, rotate
///
////////////////////////////////////////////////////////////
void zoom(float factor);
////////////////////////////////////////////////////////////
/// \brief Get the projection transform of the view
///
/// This function is meant for internal use only.
///
/// \return Projection transform defining the view
///
/// \see getInverseTransform
///
////////////////////////////////////////////////////////////
const Transform& getTransform() const;
////////////////////////////////////////////////////////////
/// \brief Get the inverse projection transform of the view
///
/// This function is meant for internal use only.
///
/// \return Inverse of the projection transform defining the view
///
/// \see getTransform
///
////////////////////////////////////////////////////////////
const Transform& getInverseTransform() const;
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Vector2f m_center; ///< Center of the view, in scene coordinates
Vector2f m_size; ///< Size of the view, in scene coordinates
float m_rotation; ///< Angle of rotation of the view rectangle, in degrees
FloatRect m_viewport; ///< Viewport rectangle, expressed as a factor of the render-target's size
mutable Transform m_transform; ///< Precomputed projection transform corresponding to the view
mutable Transform m_inverseTransform; ///< Precomputed inverse projection transform corresponding to the view
mutable bool m_transformUpdated; ///< Internal state telling if the transform needs to be updated
mutable bool m_invTransformUpdated; ///< Internal state telling if the inverse transform needs to be updated
};
} // namespace sf
#endif // SFML_VIEW_HPP
////////////////////////////////////////////////////////////
/// \class sf::View
/// \ingroup graphics
///
/// sf::View defines a camera in the 2D scene. This is a
/// very powerful concept: you can scroll, rotate or zoom
/// the entire scene without altering the way that your
/// drawable objects are drawn.
///
/// A view is composed of a source rectangle, which defines
/// what part of the 2D scene is shown, and a target viewport,
/// which defines where the contents of the source rectangle
/// will be displayed on the render target (window or texture).
///
/// The viewport allows to map the scene to a custom part
/// of the render target, and can be used for split-screen
/// or for displaying a minimap, for example. If the source
/// rectangle has not the same size as the viewport, its
/// contents will be stretched to fit in.
///
/// To apply a view, you have to assign it to the render target.
/// Then, every objects drawn in this render target will be
/// affected by the view until you use another view.
///
/// Usage example:
/// \code
/// sf::RenderWindow window;
/// sf::View view;
///
/// // Initialize the view to a rectangle located at (100, 100) and with a size of 400x200
/// view.reset(sf::FloatRect(100, 100, 400, 200));
///
/// // Rotate it by 45 degrees
/// view.rotate(45);
///
/// // Set its target viewport to be half of the window
/// view.setViewport(sf::FloatRect(0.f, 0.f, 0.5f, 1.f));
///
/// // Apply it
/// window.setView(view);
///
/// // Render stuff
/// window.draw(someSprite);
///
/// // Set the default view back
/// window.setView(window.getDefaultView());
///
/// // Render stuff not affected by the view
/// window.draw(someText);
/// \endcode
///
/// See also the note on coordinates and undistorted rendering in sf::Transformable.
///
/// \see sf::RenderWindow, sf::RenderTexture
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_VIEW_HPP
#define SFML_VIEW_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/Transform.hpp>
#include <SFML/System/Vector2.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief 2D camera that defines what region is shown on screen
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API View
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor creates a default view of (0, 0, 1000, 1000)
///
////////////////////////////////////////////////////////////
View();
////////////////////////////////////////////////////////////
/// \brief Construct the view from a rectangle
///
/// \param rectangle Rectangle defining the zone to display
///
////////////////////////////////////////////////////////////
explicit View(const FloatRect& rectangle);
////////////////////////////////////////////////////////////
/// \brief Construct the view from its center and size
///
/// \param center Center of the zone to display
/// \param size Size of zone to display
///
////////////////////////////////////////////////////////////
View(const Vector2f& center, const Vector2f& size);
////////////////////////////////////////////////////////////
/// \brief Set the center of the view
///
/// \param x X coordinate of the new center
/// \param y Y coordinate of the new center
///
/// \see setSize, getCenter
///
////////////////////////////////////////////////////////////
void setCenter(float x, float y);
////////////////////////////////////////////////////////////
/// \brief Set the center of the view
///
/// \param center New center
///
/// \see setSize, getCenter
///
////////////////////////////////////////////////////////////
void setCenter(const Vector2f& center);
////////////////////////////////////////////////////////////
/// \brief Set the size of the view
///
/// \param width New width of the view
/// \param height New height of the view
///
/// \see setCenter, getCenter
///
////////////////////////////////////////////////////////////
void setSize(float width, float height);
////////////////////////////////////////////////////////////
/// \brief Set the size of the view
///
/// \param size New size
///
/// \see setCenter, getCenter
///
////////////////////////////////////////////////////////////
void setSize(const Vector2f& size);
////////////////////////////////////////////////////////////
/// \brief Set the orientation of the view
///
/// The default rotation of a view is 0 degree.
///
/// \param angle New angle, in degrees
///
/// \see getRotation
///
////////////////////////////////////////////////////////////
void setRotation(float angle);
////////////////////////////////////////////////////////////
/// \brief Set the target viewport
///
/// The viewport is the rectangle into which the contents of the
/// view are displayed, expressed as a factor (between 0 and 1)
/// of the size of the RenderTarget to which the view is applied.
/// For example, a view which takes the left side of the target would
/// be defined with View.setViewport(sf::FloatRect(0, 0, 0.5, 1)).
/// By default, a view has a viewport which covers the entire target.
///
/// \param viewport New viewport rectangle
///
/// \see getViewport
///
////////////////////////////////////////////////////////////
void setViewport(const FloatRect& viewport);
////////////////////////////////////////////////////////////
/// \brief Reset the view to the given rectangle
///
/// Note that this function resets the rotation angle to 0.
///
/// \param rectangle Rectangle defining the zone to display
///
/// \see setCenter, setSize, setRotation
///
////////////////////////////////////////////////////////////
void reset(const FloatRect& rectangle);
////////////////////////////////////////////////////////////
/// \brief Get the center of the view
///
/// \return Center of the view
///
/// \see getSize, setCenter
///
////////////////////////////////////////////////////////////
const Vector2f& getCenter() const;
////////////////////////////////////////////////////////////
/// \brief Get the size of the view
///
/// \return Size of the view
///
/// \see getCenter, setSize
///
////////////////////////////////////////////////////////////
const Vector2f& getSize() const;
////////////////////////////////////////////////////////////
/// \brief Get the current orientation of the view
///
/// \return Rotation angle of the view, in degrees
///
/// \see setRotation
///
////////////////////////////////////////////////////////////
float getRotation() const;
////////////////////////////////////////////////////////////
/// \brief Get the target viewport rectangle of the view
///
/// \return Viewport rectangle, expressed as a factor of the target size
///
/// \see setViewport
///
////////////////////////////////////////////////////////////
const FloatRect& getViewport() const;
////////////////////////////////////////////////////////////
/// \brief Move the view relatively to its current position
///
/// \param offsetX X coordinate of the move offset
/// \param offsetY Y coordinate of the move offset
///
/// \see setCenter, rotate, zoom
///
////////////////////////////////////////////////////////////
void move(float offsetX, float offsetY);
////////////////////////////////////////////////////////////
/// \brief Move the view relatively to its current position
///
/// \param offset Move offset
///
/// \see setCenter, rotate, zoom
///
////////////////////////////////////////////////////////////
void move(const Vector2f& offset);
////////////////////////////////////////////////////////////
/// \brief Rotate the view relatively to its current orientation
///
/// \param angle Angle to rotate, in degrees
///
/// \see setRotation, move, zoom
///
////////////////////////////////////////////////////////////
void rotate(float angle);
////////////////////////////////////////////////////////////
/// \brief Resize the view rectangle relatively to its current size
///
/// Resizing the view simulates a zoom, as the zone displayed on
/// screen grows or shrinks.
/// \a factor is a multiplier:
/// \li 1 keeps the size unchanged
/// \li > 1 makes the view bigger (objects appear smaller)
/// \li < 1 makes the view smaller (objects appear bigger)
///
/// \param factor Zoom factor to apply
///
/// \see setSize, move, rotate
///
////////////////////////////////////////////////////////////
void zoom(float factor);
////////////////////////////////////////////////////////////
/// \brief Get the projection transform of the view
///
/// This function is meant for internal use only.
///
/// \return Projection transform defining the view
///
/// \see getInverseTransform
///
////////////////////////////////////////////////////////////
const Transform& getTransform() const;
////////////////////////////////////////////////////////////
/// \brief Get the inverse projection transform of the view
///
/// This function is meant for internal use only.
///
/// \return Inverse of the projection transform defining the view
///
/// \see getTransform
///
////////////////////////////////////////////////////////////
const Transform& getInverseTransform() const;
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Vector2f m_center; ///< Center of the view, in scene coordinates
Vector2f m_size; ///< Size of the view, in scene coordinates
float m_rotation; ///< Angle of rotation of the view rectangle, in degrees
FloatRect m_viewport; ///< Viewport rectangle, expressed as a factor of the render-target's size
mutable Transform m_transform; ///< Precomputed projection transform corresponding to the view
mutable Transform m_inverseTransform; ///< Precomputed inverse projection transform corresponding to the view
mutable bool m_transformUpdated; ///< Internal state telling if the transform needs to be updated
mutable bool m_invTransformUpdated; ///< Internal state telling if the inverse transform needs to be updated
};
} // namespace sf
#endif // SFML_VIEW_HPP
////////////////////////////////////////////////////////////
/// \class sf::View
/// \ingroup graphics
///
/// sf::View defines a camera in the 2D scene. This is a
/// very powerful concept: you can scroll, rotate or zoom
/// the entire scene without altering the way that your
/// drawable objects are drawn.
///
/// A view is composed of a source rectangle, which defines
/// what part of the 2D scene is shown, and a target viewport,
/// which defines where the contents of the source rectangle
/// will be displayed on the render target (window or texture).
///
/// The viewport allows to map the scene to a custom part
/// of the render target, and can be used for split-screen
/// or for displaying a minimap, for example. If the source
/// rectangle has not the same size as the viewport, its
/// contents will be stretched to fit in.
///
/// To apply a view, you have to assign it to the render target.
/// Then, every objects drawn in this render target will be
/// affected by the view until you use another view.
///
/// Usage example:
/// \code
/// sf::RenderWindow window;
/// sf::View view;
///
/// // Initialize the view to a rectangle located at (100, 100) and with a size of 400x200
/// view.reset(sf::FloatRect(100, 100, 400, 200));
///
/// // Rotate it by 45 degrees
/// view.rotate(45);
///
/// // Set its target viewport to be half of the window
/// view.setViewport(sf::FloatRect(0.f, 0.f, 0.5f, 1.f));
///
/// // Apply it
/// window.setView(view);
///
/// // Render stuff
/// window.draw(someSprite);
///
/// // Set the default view back
/// window.setView(window.getDefaultView());
///
/// // Render stuff not affected by the view
/// window.draw(someText);
/// \endcode
///
/// See also the note on coordinates and undistorted rendering in sf::Transformable.
///
/// \see sf::RenderWindow, sf::RenderTexture
///
////////////////////////////////////////////////////////////

View file

@ -1,51 +1,51 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_NETWORK_HPP
#define SFML_NETWORK_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System.hpp>
#include <SFML/Network/Ftp.hpp>
#include <SFML/Network/Http.hpp>
#include <SFML/Network/IpAddress.hpp>
#include <SFML/Network/Packet.hpp>
#include <SFML/Network/SocketSelector.hpp>
#include <SFML/Network/TcpListener.hpp>
#include <SFML/Network/TcpSocket.hpp>
#include <SFML/Network/UdpSocket.hpp>
#endif // SFML_NETWORK_HPP
////////////////////////////////////////////////////////////
/// \defgroup network Network module
///
/// Socket-based communication, utilities and higher-level
/// network protocols (HTTP, FTP).
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_NETWORK_HPP
#define SFML_NETWORK_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System.hpp>
#include <SFML/Network/Ftp.hpp>
#include <SFML/Network/Http.hpp>
#include <SFML/Network/IpAddress.hpp>
#include <SFML/Network/Packet.hpp>
#include <SFML/Network/SocketSelector.hpp>
#include <SFML/Network/TcpListener.hpp>
#include <SFML/Network/TcpSocket.hpp>
#include <SFML/Network/UdpSocket.hpp>
#endif // SFML_NETWORK_HPP
////////////////////////////////////////////////////////////
/// \defgroup network Network module
///
/// Socket-based communication, utilities and higher-level
/// network protocols (HTTP, FTP).
///
////////////////////////////////////////////////////////////

File diff suppressed because it is too large Load diff

View file

@ -1,482 +1,482 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_HTTP_HPP
#define SFML_HTTP_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/Network/IpAddress.hpp>
#include <SFML/Network/TcpSocket.hpp>
#include <SFML/System/NonCopyable.hpp>
#include <SFML/System/Time.hpp>
#include <map>
#include <string>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief A HTTP client
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API Http : NonCopyable
{
public :
////////////////////////////////////////////////////////////
/// \brief Define a HTTP request
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API Request
{
public :
////////////////////////////////////////////////////////////
/// \brief Enumerate the available HTTP methods for a request
///
////////////////////////////////////////////////////////////
enum Method
{
Get, ///< Request in get mode, standard method to retrieve a page
Post, ///< Request in post mode, usually to send data to a page
Head, ///< Request a page's header only
Put, ///< Request in put mode, useful for a REST API
Delete ///< Request in delete mode, useful for a REST API
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor creates a GET request, with the root
/// URI ("/") and an empty body.
///
/// \param uri Target URI
/// \param method Method to use for the request
/// \param body Content of the request's body
///
////////////////////////////////////////////////////////////
Request(const std::string& uri = "/", Method method = Get, const std::string& body = "");
////////////////////////////////////////////////////////////
/// \brief Set the value of a field
///
/// The field is created if it doesn't exist. The name of
/// the field is case insensitive.
/// By default, a request doesn't contain any field (but the
/// mandatory fields are added later by the HTTP client when
/// sending the request).
///
/// \param field Name of the field to set
/// \param value Value of the field
///
////////////////////////////////////////////////////////////
void setField(const std::string& field, const std::string& value);
////////////////////////////////////////////////////////////
/// \brief Set the request method
///
/// See the Method enumeration for a complete list of all
/// the availale methods.
/// The method is Http::Request::Get by default.
///
/// \param method Method to use for the request
///
////////////////////////////////////////////////////////////
void setMethod(Method method);
////////////////////////////////////////////////////////////
/// \brief Set the requested URI
///
/// The URI is the resource (usually a web page or a file)
/// that you want to get or post.
/// The URI is "/" (the root page) by default.
///
/// \param uri URI to request, relative to the host
///
////////////////////////////////////////////////////////////
void setUri(const std::string& uri);
////////////////////////////////////////////////////////////
/// \brief Set the HTTP version for the request
///
/// The HTTP version is 1.0 by default.
///
/// \param major Major HTTP version number
/// \param minor Minor HTTP version number
///
////////////////////////////////////////////////////////////
void setHttpVersion(unsigned int major, unsigned int minor);
////////////////////////////////////////////////////////////
/// \brief Set the body of the request
///
/// The body of a request is optional and only makes sense
/// for POST requests. It is ignored for all other methods.
/// The body is empty by default.
///
/// \param body Content of the body
///
////////////////////////////////////////////////////////////
void setBody(const std::string& body);
private :
friend class Http;
////////////////////////////////////////////////////////////
/// \brief Prepare the final request to send to the server
///
/// This is used internally by Http before sending the
/// request to the web server.
///
/// \return String containing the request, ready to be sent
///
////////////////////////////////////////////////////////////
std::string prepare() const;
////////////////////////////////////////////////////////////
/// \brief Check if the request defines a field
///
/// This function uses case-insensitive comparisons.
///
/// \param field Name of the field to test
///
/// \return True if the field exists, false otherwise
///
////////////////////////////////////////////////////////////
bool hasField(const std::string& field) const;
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::map<std::string, std::string> FieldTable;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
FieldTable m_fields; ///< Fields of the header associated to their value
Method m_method; ///< Method to use for the request
std::string m_uri; ///< Target URI of the request
unsigned int m_majorVersion; ///< Major HTTP version
unsigned int m_minorVersion; ///< Minor HTTP version
std::string m_body; ///< Body of the request
};
////////////////////////////////////////////////////////////
/// \brief Define a HTTP response
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API Response
{
public :
////////////////////////////////////////////////////////////
/// \brief Enumerate all the valid status codes for a response
///
////////////////////////////////////////////////////////////
enum Status
{
// 2xx: success
Ok = 200, ///< Most common code returned when operation was successful
Created = 201, ///< The resource has successfully been created
Accepted = 202, ///< The request has been accepted, but will be processed later by the server
NoContent = 204, ///< The server didn't send any data in return
ResetContent = 205, ///< The server informs the client that it should clear the view (form) that caused the request to be sent
PartialContent = 206, ///< The server has sent a part of the resource, as a response to a partial GET request
// 3xx: redirection
MultipleChoices = 300, ///< The requested page can be accessed from several locations
MovedPermanently = 301, ///< The requested page has permanently moved to a new location
MovedTemporarily = 302, ///< The requested page has temporarily moved to a new location
NotModified = 304, ///< For conditionnal requests, means the requested page hasn't changed and doesn't need to be refreshed
// 4xx: client error
BadRequest = 400, ///< The server couldn't understand the request (syntax error)
Unauthorized = 401, ///< The requested page needs an authentification to be accessed
Forbidden = 403, ///< The requested page cannot be accessed at all, even with authentification
NotFound = 404, ///< The requested page doesn't exist
RangeNotSatisfiable = 407, ///< The server can't satisfy the partial GET request (with a "Range" header field)
// 5xx: server error
InternalServerError = 500, ///< The server encountered an unexpected error
NotImplemented = 501, ///< The server doesn't implement a requested feature
BadGateway = 502, ///< The gateway server has received an error from the source server
ServiceNotAvailable = 503, ///< The server is temporarily unavailable (overloaded, in maintenance, ...)
GatewayTimeout = 504, ///< The gateway server couldn't receive a response from the source server
VersionNotSupported = 505, ///< The server doesn't support the requested HTTP version
// 10xx: SFML custom codes
InvalidResponse = 1000, ///< Response is not a valid HTTP one
ConnectionFailed = 1001 ///< Connection with server failed
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Constructs an empty response.
///
////////////////////////////////////////////////////////////
Response();
////////////////////////////////////////////////////////////
/// \brief Get the value of a field
///
/// If the field \a field is not found in the response header,
/// the empty string is returned. This function uses
/// case-insensitive comparisons.
///
/// \param field Name of the field to get
///
/// \return Value of the field, or empty string if not found
///
////////////////////////////////////////////////////////////
const std::string& getField(const std::string& field) const;
////////////////////////////////////////////////////////////
/// \brief Get the response status code
///
/// The status code should be the first thing to be checked
/// after receiving a response, it defines whether it is a
/// success, a failure or anything else (see the Status
/// enumeration).
///
/// \return Status code of the response
///
////////////////////////////////////////////////////////////
Status getStatus() const;
////////////////////////////////////////////////////////////
/// \brief Get the major HTTP version number of the response
///
/// \return Major HTTP version number
///
/// \see getMinorHttpVersion
///
////////////////////////////////////////////////////////////
unsigned int getMajorHttpVersion() const;
////////////////////////////////////////////////////////////
/// \brief Get the minor HTTP version number of the response
///
/// \return Minor HTTP version number
///
/// \see getMajorHttpVersion
///
////////////////////////////////////////////////////////////
unsigned int getMinorHttpVersion() const;
////////////////////////////////////////////////////////////
/// \brief Get the body of the response
///
/// The body of a response may contain:
/// \li the requested page (for GET requests)
/// \li a response from the server (for POST requests)
/// \li nothing (for HEAD requests)
/// \li an error message (in case of an error)
///
/// \return The response body
///
////////////////////////////////////////////////////////////
const std::string& getBody() const;
private :
friend class Http;
////////////////////////////////////////////////////////////
/// \brief Construct the header from a response string
///
/// This function is used by Http to build the response
/// of a request.
///
/// \param data Content of the response to parse
///
////////////////////////////////////////////////////////////
void parse(const std::string& data);
////////////////////////////////////////////////////////////
/// \brief Read values passed in the answer header
///
/// This function is used by Http to extract values passed
/// in the response.
///
/// \param in String stream containing the header values
///
////////////////////////////////////////////////////////////
void parseFields(std::istream &in);
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::map<std::string, std::string> FieldTable;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
FieldTable m_fields; ///< Fields of the header
Status m_status; ///< Status code
unsigned int m_majorVersion; ///< Major HTTP version
unsigned int m_minorVersion; ///< Minor HTTP version
std::string m_body; ///< Body of the response
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Http();
////////////////////////////////////////////////////////////
/// \brief Construct the HTTP client with the target host
///
/// This is equivalent to calling setHost(host, port).
/// The port has a default value of 0, which means that the
/// HTTP client will use the right port according to the
/// protocol used (80 for HTTP). You should leave it like
/// this unless you really need a port other than the
/// standard one, or use an unknown protocol.
///
/// \param host Web server to connect to
/// \param port Port to use for connection
///
////////////////////////////////////////////////////////////
Http(const std::string& host, unsigned short port = 0);
////////////////////////////////////////////////////////////
/// \brief Set the target host
///
/// This function just stores the host address and port, it
/// doesn't actually connect to it until you send a request.
/// The port has a default value of 0, which means that the
/// HTTP client will use the right port according to the
/// protocol used (80 for HTTP). You should leave it like
/// this unless you really need a port other than the
/// standard one, or use an unknown protocol.
///
/// \param host Web server to connect to
/// \param port Port to use for connection
///
////////////////////////////////////////////////////////////
void setHost(const std::string& host, unsigned short port = 0);
////////////////////////////////////////////////////////////
/// \brief Send a HTTP request and return the server's response.
///
/// You must have a valid host before sending a request (see setHost).
/// Any missing mandatory header field in the request will be added
/// with an appropriate value.
/// Warning: this function waits for the server's response and may
/// not return instantly; use a thread if you don't want to block your
/// application, or use a timeout to limit the time to wait. A value
/// of Time::Zero means that the client will use the system defaut timeout
/// (which is usually pretty long).
///
/// \param request Request to send
/// \param timeout Maximum time to wait
///
/// \return Server's response
///
////////////////////////////////////////////////////////////
Response sendRequest(const Request& request, Time timeout = Time::Zero);
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
TcpSocket m_connection; ///< Connection to the host
IpAddress m_host; ///< Web host address
std::string m_hostName; ///< Web host name
unsigned short m_port; ///< Port used for connection with host
};
} // namespace sf
#endif // SFML_HTTP_HPP
////////////////////////////////////////////////////////////
/// \class sf::Http
/// \ingroup network
///
/// sf::Http is a very simple HTTP client that allows you
/// to communicate with a web server. You can retrieve
/// web pages, send data to an interactive resource,
/// download a remote file, etc. The HTTPS protocol is
/// not supported.
///
/// The HTTP client is split into 3 classes:
/// \li sf::Http::Request
/// \li sf::Http::Response
/// \li sf::Http
///
/// sf::Http::Request builds the request that will be
/// sent to the server. A request is made of:
/// \li a method (what you want to do)
/// \li a target URI (usually the name of the web page or file)
/// \li one or more header fields (options that you can pass to the server)
/// \li an optional body (for POST requests)
///
/// sf::Http::Response parse the response from the web server
/// and provides getters to read them. The response contains:
/// \li a status code
/// \li header fields (that may be answers to the ones that you requested)
/// \li a body, which contains the contents of the requested resource
///
/// sf::Http provides a simple function, SendRequest, to send a
/// sf::Http::Request and return the corresponding sf::Http::Response
/// from the server.
///
/// Usage example:
/// \code
/// // Create a new HTTP client
/// sf::Http http;
///
/// // We'll work on http://www.sfml-dev.org
/// http.setHost("http://www.sfml-dev.org");
///
/// // Prepare a request to get the 'features.php' page
/// sf::Http::Request request("features.php");
///
/// // Send the request
/// sf::Http::Response response = http.sendRequest(request);
///
/// // Check the status code and display the result
/// sf::Http::Response::Status status = response.getStatus();
/// if (status == sf::Http::Response::Ok)
/// {
/// std::cout << response.getBody() << std::endl;
/// }
/// else
/// {
/// std::cout << "Error " << status << std::endl;
/// }
/// \endcode
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_HTTP_HPP
#define SFML_HTTP_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/Network/IpAddress.hpp>
#include <SFML/Network/TcpSocket.hpp>
#include <SFML/System/NonCopyable.hpp>
#include <SFML/System/Time.hpp>
#include <map>
#include <string>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief A HTTP client
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API Http : NonCopyable
{
public:
////////////////////////////////////////////////////////////
/// \brief Define a HTTP request
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API Request
{
public:
////////////////////////////////////////////////////////////
/// \brief Enumerate the available HTTP methods for a request
///
////////////////////////////////////////////////////////////
enum Method
{
Get, ///< Request in get mode, standard method to retrieve a page
Post, ///< Request in post mode, usually to send data to a page
Head, ///< Request a page's header only
Put, ///< Request in put mode, useful for a REST API
Delete ///< Request in delete mode, useful for a REST API
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor creates a GET request, with the root
/// URI ("/") and an empty body.
///
/// \param uri Target URI
/// \param method Method to use for the request
/// \param body Content of the request's body
///
////////////////////////////////////////////////////////////
Request(const std::string& uri = "/", Method method = Get, const std::string& body = "");
////////////////////////////////////////////////////////////
/// \brief Set the value of a field
///
/// The field is created if it doesn't exist. The name of
/// the field is case insensitive.
/// By default, a request doesn't contain any field (but the
/// mandatory fields are added later by the HTTP client when
/// sending the request).
///
/// \param field Name of the field to set
/// \param value Value of the field
///
////////////////////////////////////////////////////////////
void setField(const std::string& field, const std::string& value);
////////////////////////////////////////////////////////////
/// \brief Set the request method
///
/// See the Method enumeration for a complete list of all
/// the availale methods.
/// The method is Http::Request::Get by default.
///
/// \param method Method to use for the request
///
////////////////////////////////////////////////////////////
void setMethod(Method method);
////////////////////////////////////////////////////////////
/// \brief Set the requested URI
///
/// The URI is the resource (usually a web page or a file)
/// that you want to get or post.
/// The URI is "/" (the root page) by default.
///
/// \param uri URI to request, relative to the host
///
////////////////////////////////////////////////////////////
void setUri(const std::string& uri);
////////////////////////////////////////////////////////////
/// \brief Set the HTTP version for the request
///
/// The HTTP version is 1.0 by default.
///
/// \param major Major HTTP version number
/// \param minor Minor HTTP version number
///
////////////////////////////////////////////////////////////
void setHttpVersion(unsigned int major, unsigned int minor);
////////////////////////////////////////////////////////////
/// \brief Set the body of the request
///
/// The body of a request is optional and only makes sense
/// for POST requests. It is ignored for all other methods.
/// The body is empty by default.
///
/// \param body Content of the body
///
////////////////////////////////////////////////////////////
void setBody(const std::string& body);
private:
friend class Http;
////////////////////////////////////////////////////////////
/// \brief Prepare the final request to send to the server
///
/// This is used internally by Http before sending the
/// request to the web server.
///
/// \return String containing the request, ready to be sent
///
////////////////////////////////////////////////////////////
std::string prepare() const;
////////////////////////////////////////////////////////////
/// \brief Check if the request defines a field
///
/// This function uses case-insensitive comparisons.
///
/// \param field Name of the field to test
///
/// \return True if the field exists, false otherwise
///
////////////////////////////////////////////////////////////
bool hasField(const std::string& field) const;
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::map<std::string, std::string> FieldTable;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
FieldTable m_fields; ///< Fields of the header associated to their value
Method m_method; ///< Method to use for the request
std::string m_uri; ///< Target URI of the request
unsigned int m_majorVersion; ///< Major HTTP version
unsigned int m_minorVersion; ///< Minor HTTP version
std::string m_body; ///< Body of the request
};
////////////////////////////////////////////////////////////
/// \brief Define a HTTP response
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API Response
{
public:
////////////////////////////////////////////////////////////
/// \brief Enumerate all the valid status codes for a response
///
////////////////////////////////////////////////////////////
enum Status
{
// 2xx: success
Ok = 200, ///< Most common code returned when operation was successful
Created = 201, ///< The resource has successfully been created
Accepted = 202, ///< The request has been accepted, but will be processed later by the server
NoContent = 204, ///< The server didn't send any data in return
ResetContent = 205, ///< The server informs the client that it should clear the view (form) that caused the request to be sent
PartialContent = 206, ///< The server has sent a part of the resource, as a response to a partial GET request
// 3xx: redirection
MultipleChoices = 300, ///< The requested page can be accessed from several locations
MovedPermanently = 301, ///< The requested page has permanently moved to a new location
MovedTemporarily = 302, ///< The requested page has temporarily moved to a new location
NotModified = 304, ///< For conditionnal requests, means the requested page hasn't changed and doesn't need to be refreshed
// 4xx: client error
BadRequest = 400, ///< The server couldn't understand the request (syntax error)
Unauthorized = 401, ///< The requested page needs an authentification to be accessed
Forbidden = 403, ///< The requested page cannot be accessed at all, even with authentification
NotFound = 404, ///< The requested page doesn't exist
RangeNotSatisfiable = 407, ///< The server can't satisfy the partial GET request (with a "Range" header field)
// 5xx: server error
InternalServerError = 500, ///< The server encountered an unexpected error
NotImplemented = 501, ///< The server doesn't implement a requested feature
BadGateway = 502, ///< The gateway server has received an error from the source server
ServiceNotAvailable = 503, ///< The server is temporarily unavailable (overloaded, in maintenance, ...)
GatewayTimeout = 504, ///< The gateway server couldn't receive a response from the source server
VersionNotSupported = 505, ///< The server doesn't support the requested HTTP version
// 10xx: SFML custom codes
InvalidResponse = 1000, ///< Response is not a valid HTTP one
ConnectionFailed = 1001 ///< Connection with server failed
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Constructs an empty response.
///
////////////////////////////////////////////////////////////
Response();
////////////////////////////////////////////////////////////
/// \brief Get the value of a field
///
/// If the field \a field is not found in the response header,
/// the empty string is returned. This function uses
/// case-insensitive comparisons.
///
/// \param field Name of the field to get
///
/// \return Value of the field, or empty string if not found
///
////////////////////////////////////////////////////////////
const std::string& getField(const std::string& field) const;
////////////////////////////////////////////////////////////
/// \brief Get the response status code
///
/// The status code should be the first thing to be checked
/// after receiving a response, it defines whether it is a
/// success, a failure or anything else (see the Status
/// enumeration).
///
/// \return Status code of the response
///
////////////////////////////////////////////////////////////
Status getStatus() const;
////////////////////////////////////////////////////////////
/// \brief Get the major HTTP version number of the response
///
/// \return Major HTTP version number
///
/// \see getMinorHttpVersion
///
////////////////////////////////////////////////////////////
unsigned int getMajorHttpVersion() const;
////////////////////////////////////////////////////////////
/// \brief Get the minor HTTP version number of the response
///
/// \return Minor HTTP version number
///
/// \see getMajorHttpVersion
///
////////////////////////////////////////////////////////////
unsigned int getMinorHttpVersion() const;
////////////////////////////////////////////////////////////
/// \brief Get the body of the response
///
/// The body of a response may contain:
/// \li the requested page (for GET requests)
/// \li a response from the server (for POST requests)
/// \li nothing (for HEAD requests)
/// \li an error message (in case of an error)
///
/// \return The response body
///
////////////////////////////////////////////////////////////
const std::string& getBody() const;
private:
friend class Http;
////////////////////////////////////////////////////////////
/// \brief Construct the header from a response string
///
/// This function is used by Http to build the response
/// of a request.
///
/// \param data Content of the response to parse
///
////////////////////////////////////////////////////////////
void parse(const std::string& data);
////////////////////////////////////////////////////////////
/// \brief Read values passed in the answer header
///
/// This function is used by Http to extract values passed
/// in the response.
///
/// \param in String stream containing the header values
///
////////////////////////////////////////////////////////////
void parseFields(std::istream &in);
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
typedef std::map<std::string, std::string> FieldTable;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
FieldTable m_fields; ///< Fields of the header
Status m_status; ///< Status code
unsigned int m_majorVersion; ///< Major HTTP version
unsigned int m_minorVersion; ///< Minor HTTP version
std::string m_body; ///< Body of the response
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Http();
////////////////////////////////////////////////////////////
/// \brief Construct the HTTP client with the target host
///
/// This is equivalent to calling setHost(host, port).
/// The port has a default value of 0, which means that the
/// HTTP client will use the right port according to the
/// protocol used (80 for HTTP). You should leave it like
/// this unless you really need a port other than the
/// standard one, or use an unknown protocol.
///
/// \param host Web server to connect to
/// \param port Port to use for connection
///
////////////////////////////////////////////////////////////
Http(const std::string& host, unsigned short port = 0);
////////////////////////////////////////////////////////////
/// \brief Set the target host
///
/// This function just stores the host address and port, it
/// doesn't actually connect to it until you send a request.
/// The port has a default value of 0, which means that the
/// HTTP client will use the right port according to the
/// protocol used (80 for HTTP). You should leave it like
/// this unless you really need a port other than the
/// standard one, or use an unknown protocol.
///
/// \param host Web server to connect to
/// \param port Port to use for connection
///
////////////////////////////////////////////////////////////
void setHost(const std::string& host, unsigned short port = 0);
////////////////////////////////////////////////////////////
/// \brief Send a HTTP request and return the server's response.
///
/// You must have a valid host before sending a request (see setHost).
/// Any missing mandatory header field in the request will be added
/// with an appropriate value.
/// Warning: this function waits for the server's response and may
/// not return instantly; use a thread if you don't want to block your
/// application, or use a timeout to limit the time to wait. A value
/// of Time::Zero means that the client will use the system defaut timeout
/// (which is usually pretty long).
///
/// \param request Request to send
/// \param timeout Maximum time to wait
///
/// \return Server's response
///
////////////////////////////////////////////////////////////
Response sendRequest(const Request& request, Time timeout = Time::Zero);
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
TcpSocket m_connection; ///< Connection to the host
IpAddress m_host; ///< Web host address
std::string m_hostName; ///< Web host name
unsigned short m_port; ///< Port used for connection with host
};
} // namespace sf
#endif // SFML_HTTP_HPP
////////////////////////////////////////////////////////////
/// \class sf::Http
/// \ingroup network
///
/// sf::Http is a very simple HTTP client that allows you
/// to communicate with a web server. You can retrieve
/// web pages, send data to an interactive resource,
/// download a remote file, etc. The HTTPS protocol is
/// not supported.
///
/// The HTTP client is split into 3 classes:
/// \li sf::Http::Request
/// \li sf::Http::Response
/// \li sf::Http
///
/// sf::Http::Request builds the request that will be
/// sent to the server. A request is made of:
/// \li a method (what you want to do)
/// \li a target URI (usually the name of the web page or file)
/// \li one or more header fields (options that you can pass to the server)
/// \li an optional body (for POST requests)
///
/// sf::Http::Response parse the response from the web server
/// and provides getters to read them. The response contains:
/// \li a status code
/// \li header fields (that may be answers to the ones that you requested)
/// \li a body, which contains the contents of the requested resource
///
/// sf::Http provides a simple function, SendRequest, to send a
/// sf::Http::Request and return the corresponding sf::Http::Response
/// from the server.
///
/// Usage example:
/// \code
/// // Create a new HTTP client
/// sf::Http http;
///
/// // We'll work on http://www.sfml-dev.org
/// http.setHost("http://www.sfml-dev.org");
///
/// // Prepare a request to get the 'features.php' page
/// sf::Http::Request request("features.php");
///
/// // Send the request
/// sf::Http::Response response = http.sendRequest(request);
///
/// // Check the status code and display the result
/// sf::Http::Response::Status status = response.getStatus();
/// if (status == sf::Http::Response::Ok)
/// {
/// std::cout << response.getBody() << std::endl;
/// }
/// else
/// {
/// std::cout << "Error " << status << std::endl;
/// }
/// \endcode
///
////////////////////////////////////////////////////////////

View file

@ -1,316 +1,316 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_IPADDRESS_HPP
#define SFML_IPADDRESS_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/System/Time.hpp>
#include <istream>
#include <ostream>
#include <string>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Encapsulate an IPv4 network address
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API IpAddress
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor creates an empty (invalid) address
///
////////////////////////////////////////////////////////////
IpAddress();
////////////////////////////////////////////////////////////
/// \brief Construct the address from a string
///
/// Here \a address can be either a decimal address
/// (ex: "192.168.1.56") or a network name (ex: "localhost").
///
/// \param address IP address or network name
///
////////////////////////////////////////////////////////////
IpAddress(const std::string& address);
////////////////////////////////////////////////////////////
/// \brief Construct the address from a string
///
/// Here \a address can be either a decimal address
/// (ex: "192.168.1.56") or a network name (ex: "localhost").
/// This is equivalent to the constructor taking a std::string
/// parameter, it is defined for convenience so that the
/// implicit conversions from literal strings to IpAddress work.
///
/// \param address IP address or network name
///
////////////////////////////////////////////////////////////
IpAddress(const char* address);
////////////////////////////////////////////////////////////
/// \brief Construct the address from 4 bytes
///
/// Calling IpAddress(a, b, c, d) is equivalent to calling
/// IpAddress("a.b.c.d"), but safer as it doesn't have to
/// parse a string to get the address components.
///
/// \param byte0 First byte of the address
/// \param byte1 Second byte of the address
/// \param byte2 Third byte of the address
/// \param byte3 Fourth byte of the address
///
////////////////////////////////////////////////////////////
IpAddress(Uint8 byte0, Uint8 byte1, Uint8 byte2, Uint8 byte3);
////////////////////////////////////////////////////////////
/// \brief Construct the address from a 32-bits integer
///
/// This constructor uses the internal representation of
/// the address directly. It should be used for optimization
/// purposes, and only if you got that representation from
/// IpAddress::ToInteger().
///
/// \param address 4 bytes of the address packed into a 32-bits integer
///
/// \see toInteger
///
////////////////////////////////////////////////////////////
explicit IpAddress(Uint32 address);
////////////////////////////////////////////////////////////
/// \brief Get a string representation of the address
///
/// The returned string is the decimal representation of the
/// IP address (like "192.168.1.56"), even if it was constructed
/// from a host name.
///
/// \return String representation of the address
///
/// \see toInteger
///
////////////////////////////////////////////////////////////
std::string toString() const;
////////////////////////////////////////////////////////////
/// \brief Get an integer representation of the address
///
/// The returned number is the internal representation of the
/// address, and should be used for optimization purposes only
/// (like sending the address through a socket).
/// The integer produced by this function can then be converted
/// back to a sf::IpAddress with the proper constructor.
///
/// \return 32-bits unsigned integer representation of the address
///
/// \see toString
///
////////////////////////////////////////////////////////////
Uint32 toInteger() const;
////////////////////////////////////////////////////////////
/// \brief Get the computer's local address
///
/// The local address is the address of the computer from the
/// LAN point of view, i.e. something like 192.168.1.56. It is
/// meaningful only for communications over the local network.
/// Unlike getPublicAddress, this function is fast and may be
/// used safely anywhere.
///
/// \return Local IP address of the computer
///
/// \see getPublicAddress
///
////////////////////////////////////////////////////////////
static IpAddress getLocalAddress();
////////////////////////////////////////////////////////////
/// \brief Get the computer's public address
///
/// The public address is the address of the computer from the
/// internet point of view, i.e. something like 89.54.1.169.
/// It is necessary for communications over the world wide web.
/// The only way to get a public address is to ask it to a
/// distant website; as a consequence, this function depends on
/// both your network connection and the server, and may be
/// very slow. You should use it as few as possible. Because
/// this function depends on the network connection and on a distant
/// server, you may use a time limit if you don't want your program
/// to be possibly stuck waiting in case there is a problem; this
/// limit is deactivated by default.
///
/// \param timeout Maximum time to wait
///
/// \return Public IP address of the computer
///
/// \see getLocalAddress
///
////////////////////////////////////////////////////////////
static IpAddress getPublicAddress(Time timeout = Time::Zero);
////////////////////////////////////////////////////////////
// Static member data
////////////////////////////////////////////////////////////
static const IpAddress None; ///< Value representing an empty/invalid address
static const IpAddress LocalHost; ///< The "localhost" address (for connecting a computer to itself locally)
static const IpAddress Broadcast; ///< The "broadcast" address (for sending UDP messages to everyone on a local network)
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Uint32 m_address; ///< Address stored as an unsigned 32 bits integer
};
////////////////////////////////////////////////////////////
/// \brief Overload of == operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if both addresses are equal
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator ==(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of != operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if both addresses are different
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator !=(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of < operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if \a left is lesser than \a right
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator <(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of > operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if \a left is greater than \a right
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator >(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of <= operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if \a left is lesser or equal than \a right
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator <=(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of >= operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if \a left is greater or equal than \a right
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator >=(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of >> operator to extract an IP address from an input stream
///
/// \param stream Input stream
/// \param address IP address to extract
///
/// \return Reference to the input stream
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API std::istream& operator >>(std::istream& stream, IpAddress& address);
////////////////////////////////////////////////////////////
/// \brief Overload of << operator to print an IP address to an output stream
///
/// \param stream Output stream
/// \param address IP address to print
///
/// \return Reference to the output stream
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API std::ostream& operator <<(std::ostream& stream, const IpAddress& address);
} // namespace sf
#endif // SFML_IPADDRESS_HPP
////////////////////////////////////////////////////////////
/// \class sf::IpAddress
/// \ingroup network
///
/// sf::IpAddress is a utility class for manipulating network
/// addresses. It provides a set a implicit constructors and
/// conversion functions to easily build or transform an IP
/// address from/to various representations.
///
/// Usage example:
/// \code
/// sf::IpAddress a0; // an invalid address
/// sf::IpAddress a1 = sf::IpAddress::None; // an invalid address (same as a0)
/// sf::IpAddress a2("127.0.0.1"); // the local host address
/// sf::IpAddress a3 = sf::IpAddress::Broadcast; // the broadcast address
/// sf::IpAddress a4(192, 168, 1, 56); // a local address
/// sf::IpAddress a5("my_computer"); // a local address created from a network name
/// sf::IpAddress a6("89.54.1.169"); // a distant address
/// sf::IpAddress a7("www.google.com"); // a distant address created from a network name
/// sf::IpAddress a8 = sf::IpAddress::getLocalAddress(); // my address on the local network
/// sf::IpAddress a9 = sf::IpAddress::getPublicAddress(); // my address on the internet
/// \endcode
///
/// Note that sf::IpAddress currently doesn't support IPv6
/// nor other types of network addresses.
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_IPADDRESS_HPP
#define SFML_IPADDRESS_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/System/Time.hpp>
#include <istream>
#include <ostream>
#include <string>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Encapsulate an IPv4 network address
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API IpAddress
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor creates an empty (invalid) address
///
////////////////////////////////////////////////////////////
IpAddress();
////////////////////////////////////////////////////////////
/// \brief Construct the address from a string
///
/// Here \a address can be either a decimal address
/// (ex: "192.168.1.56") or a network name (ex: "localhost").
///
/// \param address IP address or network name
///
////////////////////////////////////////////////////////////
IpAddress(const std::string& address);
////////////////////////////////////////////////////////////
/// \brief Construct the address from a string
///
/// Here \a address can be either a decimal address
/// (ex: "192.168.1.56") or a network name (ex: "localhost").
/// This is equivalent to the constructor taking a std::string
/// parameter, it is defined for convenience so that the
/// implicit conversions from literal strings to IpAddress work.
///
/// \param address IP address or network name
///
////////////////////////////////////////////////////////////
IpAddress(const char* address);
////////////////////////////////////////////////////////////
/// \brief Construct the address from 4 bytes
///
/// Calling IpAddress(a, b, c, d) is equivalent to calling
/// IpAddress("a.b.c.d"), but safer as it doesn't have to
/// parse a string to get the address components.
///
/// \param byte0 First byte of the address
/// \param byte1 Second byte of the address
/// \param byte2 Third byte of the address
/// \param byte3 Fourth byte of the address
///
////////////////////////////////////////////////////////////
IpAddress(Uint8 byte0, Uint8 byte1, Uint8 byte2, Uint8 byte3);
////////////////////////////////////////////////////////////
/// \brief Construct the address from a 32-bits integer
///
/// This constructor uses the internal representation of
/// the address directly. It should be used for optimization
/// purposes, and only if you got that representation from
/// IpAddress::ToInteger().
///
/// \param address 4 bytes of the address packed into a 32-bits integer
///
/// \see toInteger
///
////////////////////////////////////////////////////////////
explicit IpAddress(Uint32 address);
////////////////////////////////////////////////////////////
/// \brief Get a string representation of the address
///
/// The returned string is the decimal representation of the
/// IP address (like "192.168.1.56"), even if it was constructed
/// from a host name.
///
/// \return String representation of the address
///
/// \see toInteger
///
////////////////////////////////////////////////////////////
std::string toString() const;
////////////////////////////////////////////////////////////
/// \brief Get an integer representation of the address
///
/// The returned number is the internal representation of the
/// address, and should be used for optimization purposes only
/// (like sending the address through a socket).
/// The integer produced by this function can then be converted
/// back to a sf::IpAddress with the proper constructor.
///
/// \return 32-bits unsigned integer representation of the address
///
/// \see toString
///
////////////////////////////////////////////////////////////
Uint32 toInteger() const;
////////////////////////////////////////////////////////////
/// \brief Get the computer's local address
///
/// The local address is the address of the computer from the
/// LAN point of view, i.e. something like 192.168.1.56. It is
/// meaningful only for communications over the local network.
/// Unlike getPublicAddress, this function is fast and may be
/// used safely anywhere.
///
/// \return Local IP address of the computer
///
/// \see getPublicAddress
///
////////////////////////////////////////////////////////////
static IpAddress getLocalAddress();
////////////////////////////////////////////////////////////
/// \brief Get the computer's public address
///
/// The public address is the address of the computer from the
/// internet point of view, i.e. something like 89.54.1.169.
/// It is necessary for communications over the world wide web.
/// The only way to get a public address is to ask it to a
/// distant website; as a consequence, this function depends on
/// both your network connection and the server, and may be
/// very slow. You should use it as few as possible. Because
/// this function depends on the network connection and on a distant
/// server, you may use a time limit if you don't want your program
/// to be possibly stuck waiting in case there is a problem; this
/// limit is deactivated by default.
///
/// \param timeout Maximum time to wait
///
/// \return Public IP address of the computer
///
/// \see getLocalAddress
///
////////////////////////////////////////////////////////////
static IpAddress getPublicAddress(Time timeout = Time::Zero);
////////////////////////////////////////////////////////////
// Static member data
////////////////////////////////////////////////////////////
static const IpAddress None; ///< Value representing an empty/invalid address
static const IpAddress LocalHost; ///< The "localhost" address (for connecting a computer to itself locally)
static const IpAddress Broadcast; ///< The "broadcast" address (for sending UDP messages to everyone on a local network)
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Uint32 m_address; ///< Address stored as an unsigned 32 bits integer
};
////////////////////////////////////////////////////////////
/// \brief Overload of == operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if both addresses are equal
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator ==(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of != operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if both addresses are different
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator !=(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of < operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if \a left is lesser than \a right
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator <(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of > operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if \a left is greater than \a right
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator >(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of <= operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if \a left is lesser or equal than \a right
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator <=(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of >= operator to compare two IP addresses
///
/// \param left Left operand (a IP address)
/// \param right Right operand (a IP address)
///
/// \return True if \a left is greater or equal than \a right
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API bool operator >=(const IpAddress& left, const IpAddress& right);
////////////////////////////////////////////////////////////
/// \brief Overload of >> operator to extract an IP address from an input stream
///
/// \param stream Input stream
/// \param address IP address to extract
///
/// \return Reference to the input stream
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API std::istream& operator >>(std::istream& stream, IpAddress& address);
////////////////////////////////////////////////////////////
/// \brief Overload of << operator to print an IP address to an output stream
///
/// \param stream Output stream
/// \param address IP address to print
///
/// \return Reference to the output stream
///
////////////////////////////////////////////////////////////
SFML_NETWORK_API std::ostream& operator <<(std::ostream& stream, const IpAddress& address);
} // namespace sf
#endif // SFML_IPADDRESS_HPP
////////////////////////////////////////////////////////////
/// \class sf::IpAddress
/// \ingroup network
///
/// sf::IpAddress is a utility class for manipulating network
/// addresses. It provides a set a implicit constructors and
/// conversion functions to easily build or transform an IP
/// address from/to various representations.
///
/// Usage example:
/// \code
/// sf::IpAddress a0; // an invalid address
/// sf::IpAddress a1 = sf::IpAddress::None; // an invalid address (same as a0)
/// sf::IpAddress a2("127.0.0.1"); // the local host address
/// sf::IpAddress a3 = sf::IpAddress::Broadcast; // the broadcast address
/// sf::IpAddress a4(192, 168, 1, 56); // a local address
/// sf::IpAddress a5("my_computer"); // a local address created from a network name
/// sf::IpAddress a6("89.54.1.169"); // a distant address
/// sf::IpAddress a7("www.google.com"); // a distant address created from a network name
/// sf::IpAddress a8 = sf::IpAddress::getLocalAddress(); // my address on the local network
/// sf::IpAddress a9 = sf::IpAddress::getPublicAddress(); // my address on the internet
/// \endcode
///
/// Note that sf::IpAddress currently doesn't support IPv6
/// nor other types of network addresses.
///
////////////////////////////////////////////////////////////

View file

@ -1,407 +1,407 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_PACKET_HPP
#define SFML_PACKET_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <string>
#include <vector>
namespace sf
{
class String;
class TcpSocket;
class UdpSocket;
////////////////////////////////////////////////////////////
/// \brief Utility class to build blocks of data to transfer
/// over the network
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API Packet
{
// A bool-like type that cannot be converted to integer or pointer types
typedef bool (Packet::*BoolType)(std::size_t);
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty packet.
///
////////////////////////////////////////////////////////////
Packet();
////////////////////////////////////////////////////////////
/// \brief Virtual destructor
///
////////////////////////////////////////////////////////////
virtual ~Packet();
////////////////////////////////////////////////////////////
/// \brief Append data to the end of the packet
///
/// \param data Pointer to the sequence of bytes to append
/// \param sizeInBytes Number of bytes to append
///
/// \see clear
///
////////////////////////////////////////////////////////////
void append(const void* data, std::size_t sizeInBytes);
////////////////////////////////////////////////////////////
/// \brief Clear the packet
///
/// After calling Clear, the packet is empty.
///
/// \see append
///
////////////////////////////////////////////////////////////
void clear();
////////////////////////////////////////////////////////////
/// \brief Get a pointer to the data contained in the packet
///
/// Warning: the returned pointer may become invalid after
/// you append data to the packet, therefore it should never
/// be stored.
/// The return pointer is NULL if the packet is empty.
///
/// \return Pointer to the data
///
/// \see getDataSize
///
////////////////////////////////////////////////////////////
const void* getData() const;
////////////////////////////////////////////////////////////
/// \brief Get the size of the data contained in the packet
///
/// This function returns the number of bytes pointed to by
/// what getData returns.
///
/// \return Data size, in bytes
///
/// \see getData
///
////////////////////////////////////////////////////////////
std::size_t getDataSize() const;
////////////////////////////////////////////////////////////
/// \brief Tell if the reading position has reached the
/// end of the packet
///
/// This function is useful to know if there is some data
/// left to be read, without actually reading it.
///
/// \return True if all data was read, false otherwise
///
/// \see operator bool
///
////////////////////////////////////////////////////////////
bool endOfPacket() const;
public:
////////////////////////////////////////////////////////////
/// \brief Test the validity of the packet, for reading
///
/// This operator allows to test the packet as a boolean
/// variable, to check if a reading operation was successful.
///
/// A packet will be in an invalid state if it has no more
/// data to read.
///
/// This behaviour is the same as standard C++ streams.
///
/// Usage example:
/// \code
/// float x;
/// packet >> x;
/// if (packet)
/// {
/// // ok, x was extracted successfully
/// }
///
/// // -- or --
///
/// float x;
/// if (packet >> x)
/// {
/// // ok, x was extracted successfully
/// }
/// \endcode
///
/// Don't focus on the return type, it's equivalent to bool but
/// it disallows unwanted implicit conversions to integer or
/// pointer types.
///
/// \return True if last data extraction from packet was successful
///
/// \see endOfPacket
///
////////////////////////////////////////////////////////////
operator BoolType() const;
////////////////////////////////////////////////////////////
/// Overloads of operator >> to read data from the packet
///
////////////////////////////////////////////////////////////
Packet& operator >>(bool& data);
Packet& operator >>(Int8& data);
Packet& operator >>(Uint8& data);
Packet& operator >>(Int16& data);
Packet& operator >>(Uint16& data);
Packet& operator >>(Int32& data);
Packet& operator >>(Uint32& data);
Packet& operator >>(float& data);
Packet& operator >>(double& data);
Packet& operator >>(char* data);
Packet& operator >>(std::string& data);
Packet& operator >>(wchar_t* data);
Packet& operator >>(std::wstring& data);
Packet& operator >>(String& data);
////////////////////////////////////////////////////////////
/// Overloads of operator << to write data into the packet
///
////////////////////////////////////////////////////////////
Packet& operator <<(bool data);
Packet& operator <<(Int8 data);
Packet& operator <<(Uint8 data);
Packet& operator <<(Int16 data);
Packet& operator <<(Uint16 data);
Packet& operator <<(Int32 data);
Packet& operator <<(Uint32 data);
Packet& operator <<(float data);
Packet& operator <<(double data);
Packet& operator <<(const char* data);
Packet& operator <<(const std::string& data);
Packet& operator <<(const wchar_t* data);
Packet& operator <<(const std::wstring& data);
Packet& operator <<(const String& data);
protected:
friend class TcpSocket;
friend class UdpSocket;
////////////////////////////////////////////////////////////
/// \brief Called before the packet is sent over the network
///
/// This function can be defined by derived classes to
/// transform the data before it is sent; this can be
/// used for compression, encryption, etc.
/// The function must return a pointer to the modified data,
/// as well as the number of bytes pointed.
/// The default implementation provides the packet's data
/// without transforming it.
///
/// \param size Variable to fill with the size of data to send
///
/// \return Pointer to the array of bytes to send
///
/// \see onReceive
///
////////////////////////////////////////////////////////////
virtual const void* onSend(std::size_t& size);
////////////////////////////////////////////////////////////
/// \brief Called after the packet is received over the network
///
/// This function can be defined by derived classes to
/// transform the data after it is received; this can be
/// used for uncompression, decryption, etc.
/// The function receives a pointer to the received data,
/// and must fill the packet with the transformed bytes.
/// The default implementation fills the packet directly
/// without transforming the data.
///
/// \param data Pointer to the received bytes
/// \param size Number of bytes
///
/// \see onSend
///
////////////////////////////////////////////////////////////
virtual void onReceive(const void* data, std::size_t size);
private :
////////////////////////////////////////////////////////////
/// Disallow comparisons between packets
///
////////////////////////////////////////////////////////////
bool operator ==(const Packet& right) const;
bool operator !=(const Packet& right) const;
////////////////////////////////////////////////////////////
/// \brief Check if the packet can extract a given number of bytes
///
/// This function updates accordingly the state of the packet.
///
/// \param size Size to check
///
/// \return True if \a size bytes can be read from the packet
///
////////////////////////////////////////////////////////////
bool checkSize(std::size_t size);
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
std::vector<char> m_data; ///< Data stored in the packet
std::size_t m_readPos; ///< Current reading position in the packet
bool m_isValid; ///< Reading state of the packet
};
} // namespace sf
#endif // SFML_PACKET_HPP
////////////////////////////////////////////////////////////
/// \class sf::Packet
/// \ingroup network
///
/// Packets provide a safe and easy way to serialize data,
/// in order to send it over the network using sockets
/// (sf::TcpSocket, sf::UdpSocket).
///
/// Packets solve 2 fundamental problems that arise when
/// transfering data over the network:
/// \li data is interpreted correctly according to the endianness
/// \li the bounds of the packet are preserved (one send == one receive)
///
/// The sf::Packet class provides both input and output modes.
/// It is designed to follow the behaviour of standard C++ streams,
/// using operators >> and << to extract and insert data.
///
/// It is recommended to use only fixed-size types (like sf::Int32, etc.),
/// to avoid possible differences between the sender and the receiver.
/// Indeed, the native C++ types may have different sizes on two platforms
/// and your data may be corrupted if that happens.
///
/// Usage example:
/// \code
/// sf::Uint32 x = 24;
/// std::string s = "hello";
/// double d = 5.89;
///
/// // Group the variables to send into a packet
/// sf::Packet packet;
/// packet << x << s << d;
///
/// // Send it over the network (socket is a valid sf::TcpSocket)
/// socket.send(packet);
///
/// -----------------------------------------------------------------
///
/// // Receive the packet at the other end
/// sf::Packet packet;
/// socket.receive(packet);
///
/// // Extract the variables contained in the packet
/// sf::Uint32 x;
/// std::string s;
/// double d;
/// if (packet >> x >> s >> d)
/// {
/// // Data extracted successfully...
/// }
/// \endcode
///
/// Packets have built-in operator >> and << overloads for
/// standard types:
/// \li bool
/// \li fixed-size integer types (sf::Int8/16/32, sf::Uint8/16/32)
/// \li floating point numbers (float, double)
/// \li string types (char*, wchar_t*, std::string, std::wstring, sf::String)
///
/// Like standard streams, it is also possible to define your own
/// overloads of operators >> and << in order to handle your
/// custom types.
///
/// \code
/// struct MyStruct
/// {
/// float number;
/// sf::Int8 integer;
/// std::string str;
/// };
///
/// sf::Packet& operator <<(sf::Packet& packet, const MyStruct& m)
/// {
/// return packet << m.number << m.integer << m.str;
/// }
///
/// sf::Packet& operator >>(sf::Packet& packet, MyStruct& m)
/// {
/// return packet >> m.number >> m.integer >> m.str;
/// }
/// \endcode
///
/// Packets also provide an extra feature that allows to apply
/// custom transformations to the data before it is sent,
/// and after it is received. This is typically used to
/// handle automatic compression or encryption of the data.
/// This is achieved by inheriting from sf::Packet, and overriding
/// the onSend and onReceive functions.
///
/// Here is an example:
/// \code
/// class ZipPacket : public sf::Packet
/// {
/// virtual const void* onSend(std::size_t& size)
/// {
/// const void* srcData = getData();
/// std::size_t srcSize = getDataSize();
///
/// return MySuperZipFunction(srcData, srcSize, &size);
/// }
///
/// virtual void onReceive(const void* data, std::size_t size)
/// {
/// std::size_t dstSize;
/// const void* dstData = MySuperUnzipFunction(data, size, &dstSize);
///
/// append(dstData, dstSize);
/// }
/// };
///
/// // Use like regular packets:
/// ZipPacket packet;
/// packet << x << s << d;
/// ...
/// \endcode
///
/// \see sf::TcpSocket, sf::UdpSocket
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_PACKET_HPP
#define SFML_PACKET_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <string>
#include <vector>
namespace sf
{
class String;
class TcpSocket;
class UdpSocket;
////////////////////////////////////////////////////////////
/// \brief Utility class to build blocks of data to transfer
/// over the network
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API Packet
{
// A bool-like type that cannot be converted to integer or pointer types
typedef bool (Packet::*BoolType)(std::size_t);
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty packet.
///
////////////////////////////////////////////////////////////
Packet();
////////////////////////////////////////////////////////////
/// \brief Virtual destructor
///
////////////////////////////////////////////////////////////
virtual ~Packet();
////////////////////////////////////////////////////////////
/// \brief Append data to the end of the packet
///
/// \param data Pointer to the sequence of bytes to append
/// \param sizeInBytes Number of bytes to append
///
/// \see clear
///
////////////////////////////////////////////////////////////
void append(const void* data, std::size_t sizeInBytes);
////////////////////////////////////////////////////////////
/// \brief Clear the packet
///
/// After calling Clear, the packet is empty.
///
/// \see append
///
////////////////////////////////////////////////////////////
void clear();
////////////////////////////////////////////////////////////
/// \brief Get a pointer to the data contained in the packet
///
/// Warning: the returned pointer may become invalid after
/// you append data to the packet, therefore it should never
/// be stored.
/// The return pointer is NULL if the packet is empty.
///
/// \return Pointer to the data
///
/// \see getDataSize
///
////////////////////////////////////////////////////////////
const void* getData() const;
////////////////////////////////////////////////////////////
/// \brief Get the size of the data contained in the packet
///
/// This function returns the number of bytes pointed to by
/// what getData returns.
///
/// \return Data size, in bytes
///
/// \see getData
///
////////////////////////////////////////////////////////////
std::size_t getDataSize() const;
////////////////////////////////////////////////////////////
/// \brief Tell if the reading position has reached the
/// end of the packet
///
/// This function is useful to know if there is some data
/// left to be read, without actually reading it.
///
/// \return True if all data was read, false otherwise
///
/// \see operator bool
///
////////////////////////////////////////////////////////////
bool endOfPacket() const;
public:
////////////////////////////////////////////////////////////
/// \brief Test the validity of the packet, for reading
///
/// This operator allows to test the packet as a boolean
/// variable, to check if a reading operation was successful.
///
/// A packet will be in an invalid state if it has no more
/// data to read.
///
/// This behaviour is the same as standard C++ streams.
///
/// Usage example:
/// \code
/// float x;
/// packet >> x;
/// if (packet)
/// {
/// // ok, x was extracted successfully
/// }
///
/// // -- or --
///
/// float x;
/// if (packet >> x)
/// {
/// // ok, x was extracted successfully
/// }
/// \endcode
///
/// Don't focus on the return type, it's equivalent to bool but
/// it disallows unwanted implicit conversions to integer or
/// pointer types.
///
/// \return True if last data extraction from packet was successful
///
/// \see endOfPacket
///
////////////////////////////////////////////////////////////
operator BoolType() const;
////////////////////////////////////////////////////////////
/// Overloads of operator >> to read data from the packet
///
////////////////////////////////////////////////////////////
Packet& operator >>(bool& data);
Packet& operator >>(Int8& data);
Packet& operator >>(Uint8& data);
Packet& operator >>(Int16& data);
Packet& operator >>(Uint16& data);
Packet& operator >>(Int32& data);
Packet& operator >>(Uint32& data);
Packet& operator >>(float& data);
Packet& operator >>(double& data);
Packet& operator >>(char* data);
Packet& operator >>(std::string& data);
Packet& operator >>(wchar_t* data);
Packet& operator >>(std::wstring& data);
Packet& operator >>(String& data);
////////////////////////////////////////////////////////////
/// Overloads of operator << to write data into the packet
///
////////////////////////////////////////////////////////////
Packet& operator <<(bool data);
Packet& operator <<(Int8 data);
Packet& operator <<(Uint8 data);
Packet& operator <<(Int16 data);
Packet& operator <<(Uint16 data);
Packet& operator <<(Int32 data);
Packet& operator <<(Uint32 data);
Packet& operator <<(float data);
Packet& operator <<(double data);
Packet& operator <<(const char* data);
Packet& operator <<(const std::string& data);
Packet& operator <<(const wchar_t* data);
Packet& operator <<(const std::wstring& data);
Packet& operator <<(const String& data);
protected:
friend class TcpSocket;
friend class UdpSocket;
////////////////////////////////////////////////////////////
/// \brief Called before the packet is sent over the network
///
/// This function can be defined by derived classes to
/// transform the data before it is sent; this can be
/// used for compression, encryption, etc.
/// The function must return a pointer to the modified data,
/// as well as the number of bytes pointed.
/// The default implementation provides the packet's data
/// without transforming it.
///
/// \param size Variable to fill with the size of data to send
///
/// \return Pointer to the array of bytes to send
///
/// \see onReceive
///
////////////////////////////////////////////////////////////
virtual const void* onSend(std::size_t& size);
////////////////////////////////////////////////////////////
/// \brief Called after the packet is received over the network
///
/// This function can be defined by derived classes to
/// transform the data after it is received; this can be
/// used for uncompression, decryption, etc.
/// The function receives a pointer to the received data,
/// and must fill the packet with the transformed bytes.
/// The default implementation fills the packet directly
/// without transforming the data.
///
/// \param data Pointer to the received bytes
/// \param size Number of bytes
///
/// \see onSend
///
////////////////////////////////////////////////////////////
virtual void onReceive(const void* data, std::size_t size);
private:
////////////////////////////////////////////////////////////
/// Disallow comparisons between packets
///
////////////////////////////////////////////////////////////
bool operator ==(const Packet& right) const;
bool operator !=(const Packet& right) const;
////////////////////////////////////////////////////////////
/// \brief Check if the packet can extract a given number of bytes
///
/// This function updates accordingly the state of the packet.
///
/// \param size Size to check
///
/// \return True if \a size bytes can be read from the packet
///
////////////////////////////////////////////////////////////
bool checkSize(std::size_t size);
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
std::vector<char> m_data; ///< Data stored in the packet
std::size_t m_readPos; ///< Current reading position in the packet
bool m_isValid; ///< Reading state of the packet
};
} // namespace sf
#endif // SFML_PACKET_HPP
////////////////////////////////////////////////////////////
/// \class sf::Packet
/// \ingroup network
///
/// Packets provide a safe and easy way to serialize data,
/// in order to send it over the network using sockets
/// (sf::TcpSocket, sf::UdpSocket).
///
/// Packets solve 2 fundamental problems that arise when
/// transfering data over the network:
/// \li data is interpreted correctly according to the endianness
/// \li the bounds of the packet are preserved (one send == one receive)
///
/// The sf::Packet class provides both input and output modes.
/// It is designed to follow the behaviour of standard C++ streams,
/// using operators >> and << to extract and insert data.
///
/// It is recommended to use only fixed-size types (like sf::Int32, etc.),
/// to avoid possible differences between the sender and the receiver.
/// Indeed, the native C++ types may have different sizes on two platforms
/// and your data may be corrupted if that happens.
///
/// Usage example:
/// \code
/// sf::Uint32 x = 24;
/// std::string s = "hello";
/// double d = 5.89;
///
/// // Group the variables to send into a packet
/// sf::Packet packet;
/// packet << x << s << d;
///
/// // Send it over the network (socket is a valid sf::TcpSocket)
/// socket.send(packet);
///
/// -----------------------------------------------------------------
///
/// // Receive the packet at the other end
/// sf::Packet packet;
/// socket.receive(packet);
///
/// // Extract the variables contained in the packet
/// sf::Uint32 x;
/// std::string s;
/// double d;
/// if (packet >> x >> s >> d)
/// {
/// // Data extracted successfully...
/// }
/// \endcode
///
/// Packets have built-in operator >> and << overloads for
/// standard types:
/// \li bool
/// \li fixed-size integer types (sf::Int8/16/32, sf::Uint8/16/32)
/// \li floating point numbers (float, double)
/// \li string types (char*, wchar_t*, std::string, std::wstring, sf::String)
///
/// Like standard streams, it is also possible to define your own
/// overloads of operators >> and << in order to handle your
/// custom types.
///
/// \code
/// struct MyStruct
/// {
/// float number;
/// sf::Int8 integer;
/// std::string str;
/// };
///
/// sf::Packet& operator <<(sf::Packet& packet, const MyStruct& m)
/// {
/// return packet << m.number << m.integer << m.str;
/// }
///
/// sf::Packet& operator >>(sf::Packet& packet, MyStruct& m)
/// {
/// return packet >> m.number >> m.integer >> m.str;
/// }
/// \endcode
///
/// Packets also provide an extra feature that allows to apply
/// custom transformations to the data before it is sent,
/// and after it is received. This is typically used to
/// handle automatic compression or encryption of the data.
/// This is achieved by inheriting from sf::Packet, and overriding
/// the onSend and onReceive functions.
///
/// Here is an example:
/// \code
/// class ZipPacket : public sf::Packet
/// {
/// virtual const void* onSend(std::size_t& size)
/// {
/// const void* srcData = getData();
/// std::size_t srcSize = getDataSize();
///
/// return MySuperZipFunction(srcData, srcSize, &size);
/// }
///
/// virtual void onReceive(const void* data, std::size_t size)
/// {
/// std::size_t dstSize;
/// const void* dstData = MySuperUnzipFunction(data, size, &dstSize);
///
/// append(dstData, dstSize);
/// }
/// };
///
/// // Use like regular packets:
/// ZipPacket packet;
/// packet << x << s << d;
/// ...
/// \endcode
///
/// \see sf::TcpSocket, sf::UdpSocket
///
////////////////////////////////////////////////////////////

View file

@ -1,218 +1,218 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOCKET_HPP
#define SFML_SOCKET_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/Network/SocketHandle.hpp>
#include <SFML/System/NonCopyable.hpp>
#include <vector>
namespace sf
{
class SocketSelector;
////////////////////////////////////////////////////////////
/// \brief Base class for all the socket types
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API Socket : NonCopyable
{
public :
////////////////////////////////////////////////////////////
/// \brief Status codes that may be returned by socket functions
///
////////////////////////////////////////////////////////////
enum Status
{
Done, ///< The socket has sent / received the data
NotReady, ///< The socket is not ready to send / receive data yet
Disconnected, ///< The TCP socket has been disconnected
Error ///< An unexpected error happened
};
////////////////////////////////////////////////////////////
/// \brief Some special values used by sockets
///
////////////////////////////////////////////////////////////
enum
{
AnyPort = 0 ///< Special value that tells the system to pick any available port
};
public :
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~Socket();
////////////////////////////////////////////////////////////
/// \brief Set the blocking state of the socket
///
/// In blocking mode, calls will not return until they have
/// completed their task. For example, a call to Receive in
/// blocking mode won't return until some data was actually
/// received.
/// In non-blocking mode, calls will always return immediately,
/// using the return code to signal whether there was data
/// available or not.
/// By default, all sockets are blocking.
///
/// \param blocking True to set the socket as blocking, false for non-blocking
///
/// \see isBlocking
///
////////////////////////////////////////////////////////////
void setBlocking(bool blocking);
////////////////////////////////////////////////////////////
/// \brief Tell whether the socket is in blocking or non-blocking mode
///
/// \return True if the socket is blocking, false otherwise
///
/// \see setBlocking
///
////////////////////////////////////////////////////////////
bool isBlocking() const;
protected :
////////////////////////////////////////////////////////////
/// \brief Types of protocols that the socket can use
///
////////////////////////////////////////////////////////////
enum Type
{
Tcp, ///< TCP protocol
Udp ///< UDP protocol
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor can only be accessed by derived classes.
///
/// \param type Type of the socket (TCP or UDP)
///
////////////////////////////////////////////////////////////
Socket(Type type);
////////////////////////////////////////////////////////////
/// \brief Return the internal handle of the socket
///
/// The returned handle may be invalid if the socket
/// was not created yet (or already destroyed).
/// This function can only be accessed by derived classes.
///
/// \return The internal (OS-specific) handle of the socket
///
////////////////////////////////////////////////////////////
SocketHandle getHandle() const;
////////////////////////////////////////////////////////////
/// \brief Create the internal representation of the socket
///
/// This function can only be accessed by derived classes.
///
////////////////////////////////////////////////////////////
void create();
////////////////////////////////////////////////////////////
/// \brief Create the internal representation of the socket
/// from a socket handle
///
/// This function can only be accessed by derived classes.
///
/// \param handle OS-specific handle of the socket to wrap
///
////////////////////////////////////////////////////////////
void create(SocketHandle handle);
////////////////////////////////////////////////////////////
/// \brief Close the socket gracefully
///
/// This function can only be accessed by derived classes.
///
////////////////////////////////////////////////////////////
void close();
private :
friend class SocketSelector;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Type m_type; ///< Type of the socket (TCP or UDP)
SocketHandle m_socket; ///< Socket descriptor
bool m_isBlocking; ///< Current blocking mode of the socket
};
} // namespace sf
#endif // SFML_SOCKET_HPP
////////////////////////////////////////////////////////////
/// \class sf::Socket
/// \ingroup network
///
/// This class mainly defines internal stuff to be used by
/// derived classes.
///
/// The only public features that it defines, and which
/// is therefore common to all the socket classes, is the
/// blocking state. All sockets can be set as blocking or
/// non-blocking.
///
/// In blocking mode, socket functions will hang until
/// the operation completes, which means that the entire
/// program (well, in fact the current thread if you use
/// multiple ones) will be stuck waiting for your socket
/// operation to complete.
///
/// In non-blocking mode, all the socket functions will
/// return immediately. If the socket is not ready to complete
/// the requested operation, the function simply returns
/// the proper status code (Socket::NotReady).
///
/// The default mode, which is blocking, is the one that is
/// generally used, in combination with threads or selectors.
/// The non-blocking mode is rather used in real-time
/// applications that run an endless loop that can poll
/// the socket often enough, and cannot afford blocking
/// this loop.
///
/// \see sf::TcpListener, sf::TcpSocket, sf::UdpSocket
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOCKET_HPP
#define SFML_SOCKET_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/Network/SocketHandle.hpp>
#include <SFML/System/NonCopyable.hpp>
#include <vector>
namespace sf
{
class SocketSelector;
////////////////////////////////////////////////////////////
/// \brief Base class for all the socket types
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API Socket : NonCopyable
{
public:
////////////////////////////////////////////////////////////
/// \brief Status codes that may be returned by socket functions
///
////////////////////////////////////////////////////////////
enum Status
{
Done, ///< The socket has sent / received the data
NotReady, ///< The socket is not ready to send / receive data yet
Disconnected, ///< The TCP socket has been disconnected
Error ///< An unexpected error happened
};
////////////////////////////////////////////////////////////
/// \brief Some special values used by sockets
///
////////////////////////////////////////////////////////////
enum
{
AnyPort = 0 ///< Special value that tells the system to pick any available port
};
public:
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~Socket();
////////////////////////////////////////////////////////////
/// \brief Set the blocking state of the socket
///
/// In blocking mode, calls will not return until they have
/// completed their task. For example, a call to Receive in
/// blocking mode won't return until some data was actually
/// received.
/// In non-blocking mode, calls will always return immediately,
/// using the return code to signal whether there was data
/// available or not.
/// By default, all sockets are blocking.
///
/// \param blocking True to set the socket as blocking, false for non-blocking
///
/// \see isBlocking
///
////////////////////////////////////////////////////////////
void setBlocking(bool blocking);
////////////////////////////////////////////////////////////
/// \brief Tell whether the socket is in blocking or non-blocking mode
///
/// \return True if the socket is blocking, false otherwise
///
/// \see setBlocking
///
////////////////////////////////////////////////////////////
bool isBlocking() const;
protected:
////////////////////////////////////////////////////////////
/// \brief Types of protocols that the socket can use
///
////////////////////////////////////////////////////////////
enum Type
{
Tcp, ///< TCP protocol
Udp ///< UDP protocol
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// This constructor can only be accessed by derived classes.
///
/// \param type Type of the socket (TCP or UDP)
///
////////////////////////////////////////////////////////////
Socket(Type type);
////////////////////////////////////////////////////////////
/// \brief Return the internal handle of the socket
///
/// The returned handle may be invalid if the socket
/// was not created yet (or already destroyed).
/// This function can only be accessed by derived classes.
///
/// \return The internal (OS-specific) handle of the socket
///
////////////////////////////////////////////////////////////
SocketHandle getHandle() const;
////////////////////////////////////////////////////////////
/// \brief Create the internal representation of the socket
///
/// This function can only be accessed by derived classes.
///
////////////////////////////////////////////////////////////
void create();
////////////////////////////////////////////////////////////
/// \brief Create the internal representation of the socket
/// from a socket handle
///
/// This function can only be accessed by derived classes.
///
/// \param handle OS-specific handle of the socket to wrap
///
////////////////////////////////////////////////////////////
void create(SocketHandle handle);
////////////////////////////////////////////////////////////
/// \brief Close the socket gracefully
///
/// This function can only be accessed by derived classes.
///
////////////////////////////////////////////////////////////
void close();
private:
friend class SocketSelector;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Type m_type; ///< Type of the socket (TCP or UDP)
SocketHandle m_socket; ///< Socket descriptor
bool m_isBlocking; ///< Current blocking mode of the socket
};
} // namespace sf
#endif // SFML_SOCKET_HPP
////////////////////////////////////////////////////////////
/// \class sf::Socket
/// \ingroup network
///
/// This class mainly defines internal stuff to be used by
/// derived classes.
///
/// The only public features that it defines, and which
/// is therefore common to all the socket classes, is the
/// blocking state. All sockets can be set as blocking or
/// non-blocking.
///
/// In blocking mode, socket functions will hang until
/// the operation completes, which means that the entire
/// program (well, in fact the current thread if you use
/// multiple ones) will be stuck waiting for your socket
/// operation to complete.
///
/// In non-blocking mode, all the socket functions will
/// return immediately. If the socket is not ready to complete
/// the requested operation, the function simply returns
/// the proper status code (Socket::NotReady).
///
/// The default mode, which is blocking, is the one that is
/// generally used, in combination with threads or selectors.
/// The non-blocking mode is rather used in real-time
/// applications that run an endless loop that can poll
/// the socket often enough, and cannot afford blocking
/// this loop.
///
/// \see sf::TcpListener, sf::TcpSocket, sf::UdpSocket
///
////////////////////////////////////////////////////////////

View file

@ -1,57 +1,57 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOCKETHANDLE_HPP
#define SFML_SOCKETHANDLE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
#if defined(SFML_SYSTEM_WINDOWS)
#include <basetsd.h>
#endif
namespace sf
{
////////////////////////////////////////////////////////////
// Define the low-level socket handle type, specific to
// each platform
////////////////////////////////////////////////////////////
#if defined(SFML_SYSTEM_WINDOWS)
typedef UINT_PTR SocketHandle;
#else
typedef int SocketHandle;
#endif
} // namespace sf
#endif // SFML_SOCKETHANDLE_HPP
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOCKETHANDLE_HPP
#define SFML_SOCKETHANDLE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
#if defined(SFML_SYSTEM_WINDOWS)
#include <basetsd.h>
#endif
namespace sf
{
////////////////////////////////////////////////////////////
// Define the low-level socket handle type, specific to
// each platform
////////////////////////////////////////////////////////////
#if defined(SFML_SYSTEM_WINDOWS)
typedef UINT_PTR SocketHandle;
#else
typedef int SocketHandle;
#endif
} // namespace sf
#endif // SFML_SOCKETHANDLE_HPP

View file

@ -1,263 +1,263 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOCKETSELECTOR_HPP
#define SFML_SOCKETSELECTOR_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/System/Time.hpp>
namespace sf
{
class Socket;
////////////////////////////////////////////////////////////
/// \brief Multiplexer that allows to read from multiple sockets
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API SocketSelector
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
SocketSelector();
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
SocketSelector(const SocketSelector& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~SocketSelector();
////////////////////////////////////////////////////////////
/// \brief Add a new socket to the selector
///
/// This function keeps a weak reference to the socket,
/// so you have to make sure that the socket is not destroyed
/// while it is stored in the selector.
/// This function does nothing if the socket is not valid.
///
/// \param socket Reference to the socket to add
///
/// \see remove, clear
///
////////////////////////////////////////////////////////////
void add(Socket& socket);
////////////////////////////////////////////////////////////
/// \brief Remove a socket from the selector
///
/// This function doesn't destroy the socket, it simply
/// removes the reference that the selector has to it.
///
/// \param socket Reference to the socket to remove
///
/// \see add, clear
///
////////////////////////////////////////////////////////////
void remove(Socket& socket);
////////////////////////////////////////////////////////////
/// \brief Remove all the sockets stored in the selector
///
/// This function doesn't destroy any instance, it simply
/// removes all the references that the selector has to
/// external sockets.
///
/// \see add, remove
///
////////////////////////////////////////////////////////////
void clear();
////////////////////////////////////////////////////////////
/// \brief Wait until one or more sockets are ready to receive
///
/// This function returns as soon as at least one socket has
/// some data available to be received. To know which sockets are
/// ready, use the isReady function.
/// If you use a timeout and no socket is ready before the timeout
/// is over, the function returns false.
///
/// \param timeout Maximum time to wait, (use Time::Zero for infinity)
///
/// \return True if there are sockets ready, false otherwise
///
/// \see isReady
///
////////////////////////////////////////////////////////////
bool wait(Time timeout = Time::Zero);
////////////////////////////////////////////////////////////
/// \brief Test a socket to know if it is ready to receive data
///
/// This function must be used after a call to Wait, to know
/// which sockets are ready to receive data. If a socket is
/// ready, a call to receive will never block because we know
/// that there is data available to read.
/// Note that if this function returns true for a TcpListener,
/// this means that it is ready to accept a new connection.
///
/// \param socket Socket to test
///
/// \return True if the socket is ready to read, false otherwise
///
/// \see isReady
///
////////////////////////////////////////////////////////////
bool isReady(Socket& socket) const;
////////////////////////////////////////////////////////////
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
SocketSelector& operator =(const SocketSelector& right);
private :
struct SocketSelectorImpl;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
SocketSelectorImpl* m_impl; ///< Opaque pointer to the implementation (which requires OS-specific types)
};
} // namespace sf
#endif // SFML_SOCKETSELECTOR_HPP
////////////////////////////////////////////////////////////
/// \class sf::SocketSelector
/// \ingroup network
///
/// Socket selectors provide a way to wait until some data is
/// available on a set of sockets, instead of just one. This
/// is convenient when you have multiple sockets that may
/// possibly receive data, but you don't know which one will
/// be ready first. In particular, it avoids to use a thread
/// for each socket; with selectors, a single thread can handle
/// all the sockets.
///
/// All types of sockets can be used in a selector:
/// \li sf::TcpListener
/// \li sf::TcpSocket
/// \li sf::UdpSocket
///
/// A selector doesn't store its own copies of the sockets
/// (socket classes are not copyable anyway), it simply keeps
/// a reference to the original sockets that you pass to the
/// "add" function. Therefore, you can't use the selector as a
/// socket container, you must store them oustide and make sure
/// that they are alive as long as they are used in the selector.
///
/// Using a selector is simple:
/// \li populate the selector with all the sockets that you want to observe
/// \li make it wait until there is data available on any of the sockets
/// \li test each socket to find out which ones are ready
///
/// Usage example:
/// \code
/// // Create a socket to listen to new connections
/// sf::TcpListener listener;
/// listener.listen(55001);
///
/// // Create a list to store the future clients
/// std::list<sf::TcpSocket*> clients;
///
/// // Create a selector
/// sf::SocketSelector selector;
///
/// // Add the listener to the selector
/// selector.add(listener);
///
/// // Endless loop that waits for new connections
/// while (running)
/// {
/// // Make the selector wait for data on any socket
/// if (selector.wait())
/// {
/// // Test the listener
/// if (selector.isReady(listener))
/// {
/// // The listener is ready: there is a pending connection
/// sf::TcpSocket* client = new sf::TcpSocket;
/// if (listener.accept(*client) == sf::Socket::Done)
/// {
/// // Add the new client to the clients list
/// clients.push_back(client);
///
/// // Add the new client to the selector so that we will
/// // be notified when he sends something
/// selector.add(*client);
/// }
/// else
/// {
/// // Error, we won't get a new connection, delete the socket
/// delete client;
/// }
/// }
/// else
/// {
/// // The listener socket is not ready, test all other sockets (the clients)
/// for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it)
/// {
/// sf::TcpSocket& client = **it;
/// if (selector.isReady(client))
/// {
/// // The client has sent some data, we can receive it
/// sf::Packet packet;
/// if (client.receive(packet) == sf::Socket::Done)
/// {
/// ...
/// }
/// }
/// }
/// }
/// }
/// }
/// \endcode
///
/// \see sf::Socket
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SOCKETSELECTOR_HPP
#define SFML_SOCKETSELECTOR_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/System/Time.hpp>
namespace sf
{
class Socket;
////////////////////////////////////////////////////////////
/// \brief Multiplexer that allows to read from multiple sockets
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API SocketSelector
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
SocketSelector();
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy Instance to copy
///
////////////////////////////////////////////////////////////
SocketSelector(const SocketSelector& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~SocketSelector();
////////////////////////////////////////////////////////////
/// \brief Add a new socket to the selector
///
/// This function keeps a weak reference to the socket,
/// so you have to make sure that the socket is not destroyed
/// while it is stored in the selector.
/// This function does nothing if the socket is not valid.
///
/// \param socket Reference to the socket to add
///
/// \see remove, clear
///
////////////////////////////////////////////////////////////
void add(Socket& socket);
////////////////////////////////////////////////////////////
/// \brief Remove a socket from the selector
///
/// This function doesn't destroy the socket, it simply
/// removes the reference that the selector has to it.
///
/// \param socket Reference to the socket to remove
///
/// \see add, clear
///
////////////////////////////////////////////////////////////
void remove(Socket& socket);
////////////////////////////////////////////////////////////
/// \brief Remove all the sockets stored in the selector
///
/// This function doesn't destroy any instance, it simply
/// removes all the references that the selector has to
/// external sockets.
///
/// \see add, remove
///
////////////////////////////////////////////////////////////
void clear();
////////////////////////////////////////////////////////////
/// \brief Wait until one or more sockets are ready to receive
///
/// This function returns as soon as at least one socket has
/// some data available to be received. To know which sockets are
/// ready, use the isReady function.
/// If you use a timeout and no socket is ready before the timeout
/// is over, the function returns false.
///
/// \param timeout Maximum time to wait, (use Time::Zero for infinity)
///
/// \return True if there are sockets ready, false otherwise
///
/// \see isReady
///
////////////////////////////////////////////////////////////
bool wait(Time timeout = Time::Zero);
////////////////////////////////////////////////////////////
/// \brief Test a socket to know if it is ready to receive data
///
/// This function must be used after a call to Wait, to know
/// which sockets are ready to receive data. If a socket is
/// ready, a call to receive will never block because we know
/// that there is data available to read.
/// Note that if this function returns true for a TcpListener,
/// this means that it is ready to accept a new connection.
///
/// \param socket Socket to test
///
/// \return True if the socket is ready to read, false otherwise
///
/// \see isReady
///
////////////////////////////////////////////////////////////
bool isReady(Socket& socket) const;
////////////////////////////////////////////////////////////
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
SocketSelector& operator =(const SocketSelector& right);
private:
struct SocketSelectorImpl;
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
SocketSelectorImpl* m_impl; ///< Opaque pointer to the implementation (which requires OS-specific types)
};
} // namespace sf
#endif // SFML_SOCKETSELECTOR_HPP
////////////////////////////////////////////////////////////
/// \class sf::SocketSelector
/// \ingroup network
///
/// Socket selectors provide a way to wait until some data is
/// available on a set of sockets, instead of just one. This
/// is convenient when you have multiple sockets that may
/// possibly receive data, but you don't know which one will
/// be ready first. In particular, it avoids to use a thread
/// for each socket; with selectors, a single thread can handle
/// all the sockets.
///
/// All types of sockets can be used in a selector:
/// \li sf::TcpListener
/// \li sf::TcpSocket
/// \li sf::UdpSocket
///
/// A selector doesn't store its own copies of the sockets
/// (socket classes are not copyable anyway), it simply keeps
/// a reference to the original sockets that you pass to the
/// "add" function. Therefore, you can't use the selector as a
/// socket container, you must store them oustide and make sure
/// that they are alive as long as they are used in the selector.
///
/// Using a selector is simple:
/// \li populate the selector with all the sockets that you want to observe
/// \li make it wait until there is data available on any of the sockets
/// \li test each socket to find out which ones are ready
///
/// Usage example:
/// \code
/// // Create a socket to listen to new connections
/// sf::TcpListener listener;
/// listener.listen(55001);
///
/// // Create a list to store the future clients
/// std::list<sf::TcpSocket*> clients;
///
/// // Create a selector
/// sf::SocketSelector selector;
///
/// // Add the listener to the selector
/// selector.add(listener);
///
/// // Endless loop that waits for new connections
/// while (running)
/// {
/// // Make the selector wait for data on any socket
/// if (selector.wait())
/// {
/// // Test the listener
/// if (selector.isReady(listener))
/// {
/// // The listener is ready: there is a pending connection
/// sf::TcpSocket* client = new sf::TcpSocket;
/// if (listener.accept(*client) == sf::Socket::Done)
/// {
/// // Add the new client to the clients list
/// clients.push_back(client);
///
/// // Add the new client to the selector so that we will
/// // be notified when he sends something
/// selector.add(*client);
/// }
/// else
/// {
/// // Error, we won't get a new connection, delete the socket
/// delete client;
/// }
/// }
/// else
/// {
/// // The listener socket is not ready, test all other sockets (the clients)
/// for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it)
/// {
/// sf::TcpSocket& client = **it;
/// if (selector.isReady(client))
/// {
/// // The client has sent some data, we can receive it
/// sf::Packet packet;
/// if (client.receive(packet) == sf::Socket::Done)
/// {
/// ...
/// }
/// }
/// }
/// }
/// }
/// }
/// \endcode
///
/// \see sf::Socket
///
////////////////////////////////////////////////////////////

View file

@ -1,162 +1,162 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_TCPLISTENER_HPP
#define SFML_TCPLISTENER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/Network/Socket.hpp>
namespace sf
{
class TcpSocket;
////////////////////////////////////////////////////////////
/// \brief Socket that listens to new TCP connections
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API TcpListener : public Socket
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
TcpListener();
////////////////////////////////////////////////////////////
/// \brief Get the port to which the socket is bound locally
///
/// If the socket is not listening to a port, this function
/// returns 0.
///
/// \return Port to which the socket is bound
///
/// \see listen
///
////////////////////////////////////////////////////////////
unsigned short getLocalPort() const;
////////////////////////////////////////////////////////////
/// \brief Start listening for connections
///
/// This functions makes the socket listen to the specified
/// port, waiting for new connections.
/// If the socket was previously listening to another port,
/// it will be stopped first and bound to the new port.
///
/// \param port Port to listen for new connections
///
/// \return Status code
///
/// \see accept, close
///
////////////////////////////////////////////////////////////
Status listen(unsigned short port);
////////////////////////////////////////////////////////////
/// \brief Stop listening and close the socket
///
/// This function gracefully stops the listener. If the
/// socket is not listening, this function has no effect.
///
/// \see listen
///
////////////////////////////////////////////////////////////
void close();
////////////////////////////////////////////////////////////
/// \brief Accept a new connection
///
/// If the socket is in blocking mode, this function will
/// not return until a connection is actually received.
///
/// \param socket Socket that will hold the new connection
///
/// \return Status code
///
/// \see listen
///
////////////////////////////////////////////////////////////
Status accept(TcpSocket& socket);
};
} // namespace sf
#endif // SFML_TCPLISTENER_HPP
////////////////////////////////////////////////////////////
/// \class sf::TcpListener
/// \ingroup network
///
/// A listener socket is a special type of socket that listens to
/// a given port and waits for connections on that port.
/// This is all it can do.
///
/// When a new connection is received, you must call accept and
/// the listener returns a new instance of sf::TcpSocket that
/// is properly initialized and can be used to communicate with
/// the new client.
///
/// Listener sockets are specific to the TCP protocol,
/// UDP sockets are connectionless and can therefore communicate
/// directly. As a consequence, a listener socket will always
/// return the new connections as sf::TcpSocket instances.
///
/// A listener is automatically closed on destruction, like all
/// other types of socket. However if you want to stop listening
/// before the socket is destroyed, you can call its close()
/// function.
///
/// Usage example:
/// \code
/// // Create a listener socket and make it wait for new
/// // connections on port 55001
/// sf::TcpListener listener;
/// listener.listen(55001);
///
/// // Endless loop that waits for new connections
/// while (running)
/// {
/// sf::TcpSocket client;
/// if (listener.accept(client) == sf::Socket::Done)
/// {
/// // A new client just connected!
/// std::cout << "New connection received from " << client.getRemoteAddress() << std::endl;
/// doSomethingWith(client);
/// }
/// }
/// \endcode
///
/// \see sf::TcpSocket, sf::Socket
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_TCPLISTENER_HPP
#define SFML_TCPLISTENER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/Network/Socket.hpp>
namespace sf
{
class TcpSocket;
////////////////////////////////////////////////////////////
/// \brief Socket that listens to new TCP connections
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API TcpListener : public Socket
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
TcpListener();
////////////////////////////////////////////////////////////
/// \brief Get the port to which the socket is bound locally
///
/// If the socket is not listening to a port, this function
/// returns 0.
///
/// \return Port to which the socket is bound
///
/// \see listen
///
////////////////////////////////////////////////////////////
unsigned short getLocalPort() const;
////////////////////////////////////////////////////////////
/// \brief Start listening for connections
///
/// This functions makes the socket listen to the specified
/// port, waiting for new connections.
/// If the socket was previously listening to another port,
/// it will be stopped first and bound to the new port.
///
/// \param port Port to listen for new connections
///
/// \return Status code
///
/// \see accept, close
///
////////////////////////////////////////////////////////////
Status listen(unsigned short port);
////////////////////////////////////////////////////////////
/// \brief Stop listening and close the socket
///
/// This function gracefully stops the listener. If the
/// socket is not listening, this function has no effect.
///
/// \see listen
///
////////////////////////////////////////////////////////////
void close();
////////////////////////////////////////////////////////////
/// \brief Accept a new connection
///
/// If the socket is in blocking mode, this function will
/// not return until a connection is actually received.
///
/// \param socket Socket that will hold the new connection
///
/// \return Status code
///
/// \see listen
///
////////////////////////////////////////////////////////////
Status accept(TcpSocket& socket);
};
} // namespace sf
#endif // SFML_TCPLISTENER_HPP
////////////////////////////////////////////////////////////
/// \class sf::TcpListener
/// \ingroup network
///
/// A listener socket is a special type of socket that listens to
/// a given port and waits for connections on that port.
/// This is all it can do.
///
/// When a new connection is received, you must call accept and
/// the listener returns a new instance of sf::TcpSocket that
/// is properly initialized and can be used to communicate with
/// the new client.
///
/// Listener sockets are specific to the TCP protocol,
/// UDP sockets are connectionless and can therefore communicate
/// directly. As a consequence, a listener socket will always
/// return the new connections as sf::TcpSocket instances.
///
/// A listener is automatically closed on destruction, like all
/// other types of socket. However if you want to stop listening
/// before the socket is destroyed, you can call its close()
/// function.
///
/// Usage example:
/// \code
/// // Create a listener socket and make it wait for new
/// // connections on port 55001
/// sf::TcpListener listener;
/// listener.listen(55001);
///
/// // Endless loop that waits for new connections
/// while (running)
/// {
/// sf::TcpSocket client;
/// if (listener.accept(client) == sf::Socket::Done)
/// {
/// // A new client just connected!
/// std::cout << "New connection received from " << client.getRemoteAddress() << std::endl;
/// doSomethingWith(client);
/// }
/// }
/// \endcode
///
/// \see sf::TcpSocket, sf::Socket
///
////////////////////////////////////////////////////////////

View file

@ -1,292 +1,292 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_TCPSOCKET_HPP
#define SFML_TCPSOCKET_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/Network/Socket.hpp>
#include <SFML/System/Time.hpp>
namespace sf
{
class TcpListener;
class IpAddress;
class Packet;
////////////////////////////////////////////////////////////
/// \brief Specialized socket using the TCP protocol
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API TcpSocket : public Socket
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
TcpSocket();
////////////////////////////////////////////////////////////
/// \brief Get the port to which the socket is bound locally
///
/// If the socket is not connected, this function returns 0.
///
/// \return Port to which the socket is bound
///
/// \see connect, getRemotePort
///
////////////////////////////////////////////////////////////
unsigned short getLocalPort() const;
////////////////////////////////////////////////////////////
/// \brief Get the address of the connected peer
///
/// It the socket is not connected, this function returns
/// sf::IpAddress::None.
///
/// \return Address of the remote peer
///
/// \see getRemotePort
///
////////////////////////////////////////////////////////////
IpAddress getRemoteAddress() const;
////////////////////////////////////////////////////////////
/// \brief Get the port of the connected peer to which
/// the socket is connected
///
/// If the socket is not connected, this function returns 0.
///
/// \return Remote port to which the socket is connected
///
/// \see getRemoteAddress
///
////////////////////////////////////////////////////////////
unsigned short getRemotePort() const;
////////////////////////////////////////////////////////////
/// \brief Connect the socket to a remote peer
///
/// In blocking mode, this function may take a while, especially
/// if the remote peer is not reachable. The last parameter allows
/// you to stop trying to connect after a given timeout.
/// If the socket was previously connected, it is first disconnected.
///
/// \param remoteAddress Address of the remote peer
/// \param remotePort Port of the remote peer
/// \param timeout Optional maximum time to wait
///
/// \return Status code
///
/// \see disconnect
///
////////////////////////////////////////////////////////////
Status connect(const IpAddress& remoteAddress, unsigned short remotePort, Time timeout = Time::Zero);
////////////////////////////////////////////////////////////
/// \brief Disconnect the socket from its remote peer
///
/// This function gracefully closes the connection. If the
/// socket is not connected, this function has no effect.
///
/// \see connect
///
////////////////////////////////////////////////////////////
void disconnect();
////////////////////////////////////////////////////////////
/// \brief Send raw data to the remote peer
///
/// This function will fail if the socket is not connected.
///
/// \param data Pointer to the sequence of bytes to send
/// \param size Number of bytes to send
///
/// \return Status code
///
/// \see receive
///
////////////////////////////////////////////////////////////
Status send(const void* data, std::size_t size);
////////////////////////////////////////////////////////////
/// \brief Receive raw data from the remote peer
///
/// In blocking mode, this function will wait until some
/// bytes are actually received.
/// This function will fail if the socket is not connected.
///
/// \param data Pointer to the array to fill with the received bytes
/// \param size Maximum number of bytes that can be received
/// \param received This variable is filled with the actual number of bytes received
///
/// \return Status code
///
/// \see send
///
////////////////////////////////////////////////////////////
Status receive(void* data, std::size_t size, std::size_t& received);
////////////////////////////////////////////////////////////
/// \brief Send a formatted packet of data to the remote peer
///
/// This function will fail if the socket is not connected.
///
/// \param packet Packet to send
///
/// \return Status code
///
/// \see receive
///
////////////////////////////////////////////////////////////
Status send(Packet& packet);
////////////////////////////////////////////////////////////
/// \brief Receive a formatted packet of data from the remote peer
///
/// In blocking mode, this function will wait until the whole packet
/// has been received.
/// This function will fail if the socket is not connected.
///
/// \param packet Packet to fill with the received data
///
/// \return Status code
///
/// \see send
///
////////////////////////////////////////////////////////////
Status receive(Packet& packet);
private:
friend class TcpListener;
////////////////////////////////////////////////////////////
/// \brief Structure holding the data of a pending packet
///
////////////////////////////////////////////////////////////
struct PendingPacket
{
PendingPacket();
Uint32 Size; ///< Data of packet size
std::size_t SizeReceived; ///< Number of size bytes received so far
std::vector<char> Data; ///< Data of the packet
};
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
PendingPacket m_pendingPacket; ///< Temporary data of the packet currently being received
};
} // namespace sf
#endif // SFML_TCPSOCKET_HPP
////////////////////////////////////////////////////////////
/// \class sf::TcpSocket
/// \ingroup network
///
/// TCP is a connected protocol, which means that a TCP
/// socket can only communicate with the host it is connected
/// to. It can't send or receive anything if it is not connected.
///
/// The TCP protocol is reliable but adds a slight overhead.
/// It ensures that your data will always be received in order
/// and without errors (no data corrupted, lost or duplicated).
///
/// When a socket is connected to a remote host, you can
/// retrieve informations about this host with the
/// getRemoteAddress and getRemotePort functions. You can
/// also get the local port to which the socket is bound
/// (which is automatically chosen when the socket is connected),
/// with the getLocalPort function.
///
/// Sending and receiving data can use either the low-level
/// or the high-level functions. The low-level functions
/// process a raw sequence of bytes, and cannot ensure that
/// one call to Send will exactly match one call to Receive
/// at the other end of the socket.
///
/// The high-level interface uses packets (see sf::Packet),
/// which are easier to use and provide more safety regarding
/// the data that is exchanged. You can look at the sf::Packet
/// class to get more details about how they work.
///
/// The socket is automatically disconnected when it is destroyed,
/// but if you want to explicitely close the connection while
/// the socket instance is still alive, you can call disconnect.
///
/// Usage example:
/// \code
/// // ----- The client -----
///
/// // Create a socket and connect it to 192.168.1.50 on port 55001
/// sf::TcpSocket socket;
/// socket.connect("192.168.1.50", 55001);
///
/// // Send a message to the connected host
/// std::string message = "Hi, I am a client";
/// socket.send(message.c_str(), message.size() + 1);
///
/// // Receive an answer from the server
/// char buffer[1024];
/// std::size_t received = 0;
/// socket.receive(buffer, sizeof(buffer), received);
/// std::cout << "The server said: " << buffer << std::endl;
///
/// // ----- The server -----
///
/// // Create a listener to wait for incoming connections on port 55001
/// sf::TcpListener listener;
/// listener.listen(55001);
///
/// // Wait for a connection
/// sf::TcpSocket socket;
/// listener.accept(socket);
/// std::cout << "New client connected: " << socket.getRemoteAddress() << std::endl;
///
/// // Receive a message from the client
/// char buffer[1024];
/// std::size_t received = 0;
/// socket.receive(buffer, sizeof(buffer), received);
/// std::cout << "The client said: " << buffer << std::endl;
///
/// // Send an answer
/// std::string message = "Welcome, client";
/// socket.send(message.c_str(), message.size() + 1);
/// \endcode
///
/// \see sf::Socket, sf::UdpSocket, sf::Packet
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_TCPSOCKET_HPP
#define SFML_TCPSOCKET_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/Network/Socket.hpp>
#include <SFML/System/Time.hpp>
namespace sf
{
class TcpListener;
class IpAddress;
class Packet;
////////////////////////////////////////////////////////////
/// \brief Specialized socket using the TCP protocol
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API TcpSocket : public Socket
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
TcpSocket();
////////////////////////////////////////////////////////////
/// \brief Get the port to which the socket is bound locally
///
/// If the socket is not connected, this function returns 0.
///
/// \return Port to which the socket is bound
///
/// \see connect, getRemotePort
///
////////////////////////////////////////////////////////////
unsigned short getLocalPort() const;
////////////////////////////////////////////////////////////
/// \brief Get the address of the connected peer
///
/// It the socket is not connected, this function returns
/// sf::IpAddress::None.
///
/// \return Address of the remote peer
///
/// \see getRemotePort
///
////////////////////////////////////////////////////////////
IpAddress getRemoteAddress() const;
////////////////////////////////////////////////////////////
/// \brief Get the port of the connected peer to which
/// the socket is connected
///
/// If the socket is not connected, this function returns 0.
///
/// \return Remote port to which the socket is connected
///
/// \see getRemoteAddress
///
////////////////////////////////////////////////////////////
unsigned short getRemotePort() const;
////////////////////////////////////////////////////////////
/// \brief Connect the socket to a remote peer
///
/// In blocking mode, this function may take a while, especially
/// if the remote peer is not reachable. The last parameter allows
/// you to stop trying to connect after a given timeout.
/// If the socket was previously connected, it is first disconnected.
///
/// \param remoteAddress Address of the remote peer
/// \param remotePort Port of the remote peer
/// \param timeout Optional maximum time to wait
///
/// \return Status code
///
/// \see disconnect
///
////////////////////////////////////////////////////////////
Status connect(const IpAddress& remoteAddress, unsigned short remotePort, Time timeout = Time::Zero);
////////////////////////////////////////////////////////////
/// \brief Disconnect the socket from its remote peer
///
/// This function gracefully closes the connection. If the
/// socket is not connected, this function has no effect.
///
/// \see connect
///
////////////////////////////////////////////////////////////
void disconnect();
////////////////////////////////////////////////////////////
/// \brief Send raw data to the remote peer
///
/// This function will fail if the socket is not connected.
///
/// \param data Pointer to the sequence of bytes to send
/// \param size Number of bytes to send
///
/// \return Status code
///
/// \see receive
///
////////////////////////////////////////////////////////////
Status send(const void* data, std::size_t size);
////////////////////////////////////////////////////////////
/// \brief Receive raw data from the remote peer
///
/// In blocking mode, this function will wait until some
/// bytes are actually received.
/// This function will fail if the socket is not connected.
///
/// \param data Pointer to the array to fill with the received bytes
/// \param size Maximum number of bytes that can be received
/// \param received This variable is filled with the actual number of bytes received
///
/// \return Status code
///
/// \see send
///
////////////////////////////////////////////////////////////
Status receive(void* data, std::size_t size, std::size_t& received);
////////////////////////////////////////////////////////////
/// \brief Send a formatted packet of data to the remote peer
///
/// This function will fail if the socket is not connected.
///
/// \param packet Packet to send
///
/// \return Status code
///
/// \see receive
///
////////////////////////////////////////////////////////////
Status send(Packet& packet);
////////////////////////////////////////////////////////////
/// \brief Receive a formatted packet of data from the remote peer
///
/// In blocking mode, this function will wait until the whole packet
/// has been received.
/// This function will fail if the socket is not connected.
///
/// \param packet Packet to fill with the received data
///
/// \return Status code
///
/// \see send
///
////////////////////////////////////////////////////////////
Status receive(Packet& packet);
private:
friend class TcpListener;
////////////////////////////////////////////////////////////
/// \brief Structure holding the data of a pending packet
///
////////////////////////////////////////////////////////////
struct PendingPacket
{
PendingPacket();
Uint32 Size; ///< Data of packet size
std::size_t SizeReceived; ///< Number of size bytes received so far
std::vector<char> Data; ///< Data of the packet
};
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
PendingPacket m_pendingPacket; ///< Temporary data of the packet currently being received
};
} // namespace sf
#endif // SFML_TCPSOCKET_HPP
////////////////////////////////////////////////////////////
/// \class sf::TcpSocket
/// \ingroup network
///
/// TCP is a connected protocol, which means that a TCP
/// socket can only communicate with the host it is connected
/// to. It can't send or receive anything if it is not connected.
///
/// The TCP protocol is reliable but adds a slight overhead.
/// It ensures that your data will always be received in order
/// and without errors (no data corrupted, lost or duplicated).
///
/// When a socket is connected to a remote host, you can
/// retrieve informations about this host with the
/// getRemoteAddress and getRemotePort functions. You can
/// also get the local port to which the socket is bound
/// (which is automatically chosen when the socket is connected),
/// with the getLocalPort function.
///
/// Sending and receiving data can use either the low-level
/// or the high-level functions. The low-level functions
/// process a raw sequence of bytes, and cannot ensure that
/// one call to Send will exactly match one call to Receive
/// at the other end of the socket.
///
/// The high-level interface uses packets (see sf::Packet),
/// which are easier to use and provide more safety regarding
/// the data that is exchanged. You can look at the sf::Packet
/// class to get more details about how they work.
///
/// The socket is automatically disconnected when it is destroyed,
/// but if you want to explicitely close the connection while
/// the socket instance is still alive, you can call disconnect.
///
/// Usage example:
/// \code
/// // ----- The client -----
///
/// // Create a socket and connect it to 192.168.1.50 on port 55001
/// sf::TcpSocket socket;
/// socket.connect("192.168.1.50", 55001);
///
/// // Send a message to the connected host
/// std::string message = "Hi, I am a client";
/// socket.send(message.c_str(), message.size() + 1);
///
/// // Receive an answer from the server
/// char buffer[1024];
/// std::size_t received = 0;
/// socket.receive(buffer, sizeof(buffer), received);
/// std::cout << "The server said: " << buffer << std::endl;
///
/// // ----- The server -----
///
/// // Create a listener to wait for incoming connections on port 55001
/// sf::TcpListener listener;
/// listener.listen(55001);
///
/// // Wait for a connection
/// sf::TcpSocket socket;
/// listener.accept(socket);
/// std::cout << "New client connected: " << socket.getRemoteAddress() << std::endl;
///
/// // Receive a message from the client
/// char buffer[1024];
/// std::size_t received = 0;
/// socket.receive(buffer, sizeof(buffer), received);
/// std::cout << "The client said: " << buffer << std::endl;
///
/// // Send an answer
/// std::string message = "Welcome, client";
/// socket.send(message.c_str(), message.size() + 1);
/// \endcode
///
/// \see sf::Socket, sf::UdpSocket, sf::Packet
///
////////////////////////////////////////////////////////////

View file

@ -1,283 +1,283 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_UDPSOCKET_HPP
#define SFML_UDPSOCKET_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/Network/Socket.hpp>
#include <vector>
namespace sf
{
class IpAddress;
class Packet;
////////////////////////////////////////////////////////////
/// \brief Specialized socket using the UDP protocol
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API UdpSocket : public Socket
{
public :
////////////////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////////////////
enum
{
MaxDatagramSize = 65507 ///< The maximum number of bytes that can be sent in a single UDP datagram
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
UdpSocket();
////////////////////////////////////////////////////////////
/// \brief Get the port to which the socket is bound locally
///
/// If the socket is not bound to a port, this function
/// returns 0.
///
/// \return Port to which the socket is bound
///
/// \see bind
///
////////////////////////////////////////////////////////////
unsigned short getLocalPort() const;
////////////////////////////////////////////////////////////
/// \brief Bind the socket to a specific port
///
/// Binding the socket to a port is necessary for being
/// able to receive data on that port.
/// You can use the special value Socket::AnyPort to tell the
/// system to automatically pick an available port, and then
/// call getLocalPort to retrieve the chosen port.
///
/// \param port Port to bind the socket to
///
/// \return Status code
///
/// \see unbind, getLocalPort
///
////////////////////////////////////////////////////////////
Status bind(unsigned short port);
////////////////////////////////////////////////////////////
/// \brief Unbind the socket from the local port to which it is bound
///
/// The port that the socket was previously using is immediately
/// available after this function is called. If the
/// socket is not bound to a port, this function has no effect.
///
/// \see bind
///
////////////////////////////////////////////////////////////
void unbind();
////////////////////////////////////////////////////////////
/// \brief Send raw data to a remote peer
///
/// Make sure that \a size is not greater than
/// UdpSocket::MaxDatagramSize, otherwise this function will
/// fail and no data will be sent.
///
/// \param data Pointer to the sequence of bytes to send
/// \param size Number of bytes to send
/// \param remoteAddress Address of the receiver
/// \param remotePort Port of the receiver to send the data to
///
/// \return Status code
///
/// \see receive
///
////////////////////////////////////////////////////////////
Status send(const void* data, std::size_t size, const IpAddress& remoteAddress, unsigned short remotePort);
////////////////////////////////////////////////////////////
/// \brief Receive raw data from a remote peer
///
/// In blocking mode, this function will wait until some
/// bytes are actually received.
/// Be careful to use a buffer which is large enough for
/// the data that you intend to receive, if it is too small
/// then an error will be returned and *all* the data will
/// be lost.
///
/// \param data Pointer to the array to fill with the received bytes
/// \param size Maximum number of bytes that can be received
/// \param received This variable is filled with the actual number of bytes received
/// \param remoteAddress Address of the peer that sent the data
/// \param remotePort Port of the peer that sent the data
///
/// \return Status code
///
/// \see send
///
////////////////////////////////////////////////////////////
Status receive(void* data, std::size_t size, std::size_t& received, IpAddress& remoteAddress, unsigned short& remotePort);
////////////////////////////////////////////////////////////
/// \brief Send a formatted packet of data to a remote peer
///
/// Make sure that the packet size is not greater than
/// UdpSocket::MaxDatagramSize, otherwise this function will
/// fail and no data will be sent.
///
/// \param packet Packet to send
/// \param remoteAddress Address of the receiver
/// \param remotePort Port of the receiver to send the data to
///
/// \return Status code
///
/// \see receive
///
////////////////////////////////////////////////////////////
Status send(Packet& packet, const IpAddress& remoteAddress, unsigned short remotePort);
////////////////////////////////////////////////////////////
/// \brief Receive a formatted packet of data from a remote peer
///
/// In blocking mode, this function will wait until the whole packet
/// has been received.
///
/// \param packet Packet to fill with the received data
/// \param remoteAddress Address of the peer that sent the data
/// \param remotePort Port of the peer that sent the data
///
/// \return Status code
///
/// \see send
///
////////////////////////////////////////////////////////////
Status receive(Packet& packet, IpAddress& remoteAddress, unsigned short& remotePort);
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
std::vector<char> m_buffer; ///< Temporary buffer holding the received data in Receive(Packet)
};
} // namespace sf
#endif // SFML_UDPSOCKET_HPP
////////////////////////////////////////////////////////////
/// \class sf::UdpSocket
/// \ingroup network
///
/// A UDP socket is a connectionless socket. Instead of
/// connecting once to a remote host, like TCP sockets,
/// it can send to and receive from any host at any time.
///
/// It is a datagram protocol: bounded blocks of data (datagrams)
/// are transfered over the network rather than a continuous
/// stream of data (TCP). Therefore, one call to send will always
/// match one call to receive (if the datagram is not lost),
/// with the same data that was sent.
///
/// The UDP protocol is lightweight but unreliable. Unreliable
/// means that datagrams may be duplicated, be lost or
/// arrive reordered. However, if a datagram arrives, its
/// data is guaranteed to be valid.
///
/// UDP is generally used for real-time communication
/// (audio or video streaming, real-time games, etc.) where
/// speed is crucial and lost data doesn't matter much.
///
/// Sending and receiving data can use either the low-level
/// or the high-level functions. The low-level functions
/// process a raw sequence of bytes, whereas the high-level
/// interface uses packets (see sf::Packet), which are easier
/// to use and provide more safety regarding the data that is
/// exchanged. You can look at the sf::Packet class to get
/// more details about how they work.
///
/// It is important to note that UdpSocket is unable to send
/// datagrams bigger than MaxDatagramSize. In this case, it
/// returns an error and doesn't send anything. This applies
/// to both raw data and packets. Indeed, even packets are
/// unable to split and recompose data, due to the unreliability
/// of the protocol (dropped, mixed or duplicated datagrams may
/// lead to a big mess when trying to recompose a packet).
///
/// If the socket is bound to a port, it is automatically
/// unbound from it when the socket is destroyed. However,
/// you can unbind the socket explicitely with the Unbind
/// function if necessary, to stop receiving messages or
/// make the port available for other sockets.
///
/// Usage example:
/// \code
/// // ----- The client -----
///
/// // Create a socket and bind it to the port 55001
/// sf::UdpSocket socket;
/// socket.bind(55001);
///
/// // Send a message to 192.168.1.50 on port 55002
/// std::string message = "Hi, I am " + sf::IpAddress::getLocalAddress().toString();
/// socket.send(message.c_str(), message.size() + 1, "192.168.1.50", 55002);
///
/// // Receive an answer (most likely from 192.168.1.50, but could be anyone else)
/// char buffer[1024];
/// std::size_t received = 0;
/// sf::IpAddress sender;
/// unsigned short port;
/// socket.receive(buffer, sizeof(buffer), received, sender, port);
/// std::cout << sender.ToString() << " said: " << buffer << std::endl;
///
/// // ----- The server -----
///
/// // Create a socket and bind it to the port 55002
/// sf::UdpSocket socket;
/// socket.bind(55002);
///
/// // Receive a message from anyone
/// char buffer[1024];
/// std::size_t received = 0;
/// sf::IpAddress sender;
/// unsigned short port;
/// socket.receive(buffer, sizeof(buffer), received, sender, port);
/// std::cout << sender.ToString() << " said: " << buffer << std::endl;
///
/// // Send an answer
/// std::string message = "Welcome " + sender.toString();
/// socket.send(message.c_str(), message.size() + 1, sender, port);
/// \endcode
///
/// \see sf::Socket, sf::TcpSocket, sf::Packet
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_UDPSOCKET_HPP
#define SFML_UDPSOCKET_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Export.hpp>
#include <SFML/Network/Socket.hpp>
#include <vector>
namespace sf
{
class IpAddress;
class Packet;
////////////////////////////////////////////////////////////
/// \brief Specialized socket using the UDP protocol
///
////////////////////////////////////////////////////////////
class SFML_NETWORK_API UdpSocket : public Socket
{
public:
////////////////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////////////////
enum
{
MaxDatagramSize = 65507 ///< The maximum number of bytes that can be sent in a single UDP datagram
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
UdpSocket();
////////////////////////////////////////////////////////////
/// \brief Get the port to which the socket is bound locally
///
/// If the socket is not bound to a port, this function
/// returns 0.
///
/// \return Port to which the socket is bound
///
/// \see bind
///
////////////////////////////////////////////////////////////
unsigned short getLocalPort() const;
////////////////////////////////////////////////////////////
/// \brief Bind the socket to a specific port
///
/// Binding the socket to a port is necessary for being
/// able to receive data on that port.
/// You can use the special value Socket::AnyPort to tell the
/// system to automatically pick an available port, and then
/// call getLocalPort to retrieve the chosen port.
///
/// \param port Port to bind the socket to
///
/// \return Status code
///
/// \see unbind, getLocalPort
///
////////////////////////////////////////////////////////////
Status bind(unsigned short port);
////////////////////////////////////////////////////////////
/// \brief Unbind the socket from the local port to which it is bound
///
/// The port that the socket was previously using is immediately
/// available after this function is called. If the
/// socket is not bound to a port, this function has no effect.
///
/// \see bind
///
////////////////////////////////////////////////////////////
void unbind();
////////////////////////////////////////////////////////////
/// \brief Send raw data to a remote peer
///
/// Make sure that \a size is not greater than
/// UdpSocket::MaxDatagramSize, otherwise this function will
/// fail and no data will be sent.
///
/// \param data Pointer to the sequence of bytes to send
/// \param size Number of bytes to send
/// \param remoteAddress Address of the receiver
/// \param remotePort Port of the receiver to send the data to
///
/// \return Status code
///
/// \see receive
///
////////////////////////////////////////////////////////////
Status send(const void* data, std::size_t size, const IpAddress& remoteAddress, unsigned short remotePort);
////////////////////////////////////////////////////////////
/// \brief Receive raw data from a remote peer
///
/// In blocking mode, this function will wait until some
/// bytes are actually received.
/// Be careful to use a buffer which is large enough for
/// the data that you intend to receive, if it is too small
/// then an error will be returned and *all* the data will
/// be lost.
///
/// \param data Pointer to the array to fill with the received bytes
/// \param size Maximum number of bytes that can be received
/// \param received This variable is filled with the actual number of bytes received
/// \param remoteAddress Address of the peer that sent the data
/// \param remotePort Port of the peer that sent the data
///
/// \return Status code
///
/// \see send
///
////////////////////////////////////////////////////////////
Status receive(void* data, std::size_t size, std::size_t& received, IpAddress& remoteAddress, unsigned short& remotePort);
////////////////////////////////////////////////////////////
/// \brief Send a formatted packet of data to a remote peer
///
/// Make sure that the packet size is not greater than
/// UdpSocket::MaxDatagramSize, otherwise this function will
/// fail and no data will be sent.
///
/// \param packet Packet to send
/// \param remoteAddress Address of the receiver
/// \param remotePort Port of the receiver to send the data to
///
/// \return Status code
///
/// \see receive
///
////////////////////////////////////////////////////////////
Status send(Packet& packet, const IpAddress& remoteAddress, unsigned short remotePort);
////////////////////////////////////////////////////////////
/// \brief Receive a formatted packet of data from a remote peer
///
/// In blocking mode, this function will wait until the whole packet
/// has been received.
///
/// \param packet Packet to fill with the received data
/// \param remoteAddress Address of the peer that sent the data
/// \param remotePort Port of the peer that sent the data
///
/// \return Status code
///
/// \see send
///
////////////////////////////////////////////////////////////
Status receive(Packet& packet, IpAddress& remoteAddress, unsigned short& remotePort);
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
std::vector<char> m_buffer; ///< Temporary buffer holding the received data in Receive(Packet)
};
} // namespace sf
#endif // SFML_UDPSOCKET_HPP
////////////////////////////////////////////////////////////
/// \class sf::UdpSocket
/// \ingroup network
///
/// A UDP socket is a connectionless socket. Instead of
/// connecting once to a remote host, like TCP sockets,
/// it can send to and receive from any host at any time.
///
/// It is a datagram protocol: bounded blocks of data (datagrams)
/// are transfered over the network rather than a continuous
/// stream of data (TCP). Therefore, one call to send will always
/// match one call to receive (if the datagram is not lost),
/// with the same data that was sent.
///
/// The UDP protocol is lightweight but unreliable. Unreliable
/// means that datagrams may be duplicated, be lost or
/// arrive reordered. However, if a datagram arrives, its
/// data is guaranteed to be valid.
///
/// UDP is generally used for real-time communication
/// (audio or video streaming, real-time games, etc.) where
/// speed is crucial and lost data doesn't matter much.
///
/// Sending and receiving data can use either the low-level
/// or the high-level functions. The low-level functions
/// process a raw sequence of bytes, whereas the high-level
/// interface uses packets (see sf::Packet), which are easier
/// to use and provide more safety regarding the data that is
/// exchanged. You can look at the sf::Packet class to get
/// more details about how they work.
///
/// It is important to note that UdpSocket is unable to send
/// datagrams bigger than MaxDatagramSize. In this case, it
/// returns an error and doesn't send anything. This applies
/// to both raw data and packets. Indeed, even packets are
/// unable to split and recompose data, due to the unreliability
/// of the protocol (dropped, mixed or duplicated datagrams may
/// lead to a big mess when trying to recompose a packet).
///
/// If the socket is bound to a port, it is automatically
/// unbound from it when the socket is destroyed. However,
/// you can unbind the socket explicitely with the Unbind
/// function if necessary, to stop receiving messages or
/// make the port available for other sockets.
///
/// Usage example:
/// \code
/// // ----- The client -----
///
/// // Create a socket and bind it to the port 55001
/// sf::UdpSocket socket;
/// socket.bind(55001);
///
/// // Send a message to 192.168.1.50 on port 55002
/// std::string message = "Hi, I am " + sf::IpAddress::getLocalAddress().toString();
/// socket.send(message.c_str(), message.size() + 1, "192.168.1.50", 55002);
///
/// // Receive an answer (most likely from 192.168.1.50, but could be anyone else)
/// char buffer[1024];
/// std::size_t received = 0;
/// sf::IpAddress sender;
/// unsigned short port;
/// socket.receive(buffer, sizeof(buffer), received, sender, port);
/// std::cout << sender.ToString() << " said: " << buffer << std::endl;
///
/// // ----- The server -----
///
/// // Create a socket and bind it to the port 55002
/// sf::UdpSocket socket;
/// socket.bind(55002);
///
/// // Receive a message from anyone
/// char buffer[1024];
/// std::size_t received = 0;
/// sf::IpAddress sender;
/// unsigned short port;
/// socket.receive(buffer, sizeof(buffer), received, sender, port);
/// std::cout << sender.ToString() << " said: " << buffer << std::endl;
///
/// // Send an answer
/// std::string message = "Welcome " + sender.toString();
/// socket.send(message.c_str(), message.size() + 1, sender, port);
/// \endcode
///
/// \see sf::Socket, sf::TcpSocket, sf::Packet
///
////////////////////////////////////////////////////////////

View file

@ -1,77 +1,77 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_OPENGL_HPP
#define SFML_OPENGL_HPP
////////////////////////////////////////////////////////////
/// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
////////////////////////////////////////////////////////////
/// This file just includes the OpenGL (GL and GLU) headers,
/// which have actually different paths on each system
////////////////////////////////////////////////////////////
#if defined(SFML_SYSTEM_WINDOWS)
// The Visual C++ version of gl.h uses WINGDIAPI and APIENTRY but doesn't define them
#ifdef _MSC_VER
#include <windows.h>
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD)
#if defined(SFML_OPENGL_ES)
#include <GLES/gl.h>
#include <GLES/glext.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#elif defined(SFML_SYSTEM_MACOS)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#elif defined (SFML_SYSTEM_IOS)
#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>
#elif defined (SFML_SYSTEM_ANDROID)
#include <GLES/gl.h>
#include <GLES/glext.h>
#endif
#endif // SFML_OPENGL_HPP
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_OPENGL_HPP
#define SFML_OPENGL_HPP
////////////////////////////////////////////////////////////
/// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
////////////////////////////////////////////////////////////
/// This file just includes the OpenGL (GL and GLU) headers,
/// which have actually different paths on each system
////////////////////////////////////////////////////////////
#if defined(SFML_SYSTEM_WINDOWS)
// The Visual C++ version of gl.h uses WINGDIAPI and APIENTRY but doesn't define them
#ifdef _MSC_VER
#include <windows.h>
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD)
#if defined(SFML_OPENGL_ES)
#include <GLES/gl.h>
#include <GLES/glext.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#elif defined(SFML_SYSTEM_MACOS)
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#elif defined (SFML_SYSTEM_IOS)
#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>
#elif defined (SFML_SYSTEM_ANDROID)
#include <GLES/gl.h>
#include <GLES/glext.h>
#endif
#endif // SFML_OPENGL_HPP

View file

@ -1,56 +1,56 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SYSTEM_HPP
#define SFML_SYSTEM_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/System/Err.hpp>
#include <SFML/System/InputStream.hpp>
#include <SFML/System/Lock.hpp>
#include <SFML/System/Mutex.hpp>
#include <SFML/System/Sleep.hpp>
#include <SFML/System/String.hpp>
#include <SFML/System/Thread.hpp>
#include <SFML/System/ThreadLocal.hpp>
#include <SFML/System/ThreadLocalPtr.hpp>
#include <SFML/System/Utf.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/Vector3.hpp>
#endif // SFML_SYSTEM_HPP
////////////////////////////////////////////////////////////
/// \defgroup system System module
///
/// Base module of SFML, defining various utilities. It provides
/// vector classes, unicode strings and conversion functions,
/// threads and mutexes, timing classes.
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SYSTEM_HPP
#define SFML_SYSTEM_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/System/Err.hpp>
#include <SFML/System/InputStream.hpp>
#include <SFML/System/Lock.hpp>
#include <SFML/System/Mutex.hpp>
#include <SFML/System/Sleep.hpp>
#include <SFML/System/String.hpp>
#include <SFML/System/Thread.hpp>
#include <SFML/System/ThreadLocal.hpp>
#include <SFML/System/ThreadLocalPtr.hpp>
#include <SFML/System/Utf.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/Vector3.hpp>
#endif // SFML_SYSTEM_HPP
////////////////////////////////////////////////////////////
/// \defgroup system System module
///
/// Base module of SFML, defining various utilities. It provides
/// vector classes, unicode strings and conversion functions,
/// threads and mutexes, timing classes.
///
////////////////////////////////////////////////////////////

View file

@ -1,117 +1,117 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_CLOCK_HPP
#define SFML_CLOCK_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <SFML/System/Time.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility class that measures the elapsed time
///
////////////////////////////////////////////////////////////
class SFML_SYSTEM_API Clock
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// The clock starts automatically after being constructed.
///
////////////////////////////////////////////////////////////
Clock();
////////////////////////////////////////////////////////////
/// \brief Get the elapsed time
///
/// This function returns the time elapsed since the last call
/// to restart() (or the construction of the instance if restart()
/// has not been called).
///
/// \return Time elapsed
///
////////////////////////////////////////////////////////////
Time getElapsedTime() const;
////////////////////////////////////////////////////////////
/// \brief Restart the clock
///
/// This function puts the time counter back to zero.
/// It also returns the time elapsed since the clock was started.
///
/// \return Time elapsed
///
////////////////////////////////////////////////////////////
Time restart();
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Time m_startTime; ///< Time of last reset, in microseconds
};
} // namespace sf
#endif // SFML_CLOCK_HPP
////////////////////////////////////////////////////////////
/// \class sf::Clock
/// \ingroup system
///
/// sf::Clock is a lightweight class for measuring time.
///
/// Its provides the most precise time that the underlying
/// OS can achieve (generally microseconds or nanoseconds).
/// It also ensures monotonicity, which means that the returned
/// time can never go backward, even if the system time is
/// changed.
///
/// Usage example:
/// \code
/// sf::Clock clock;
/// ...
/// Time time1 = clock.getElapsedTime();
/// ...
/// Time time2 = clock.restart();
/// \endcode
///
/// The sf::Time value returned by the clock can then be
/// converted to a number of seconds, milliseconds or even
/// microseconds.
///
/// \see sf::Time
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_CLOCK_HPP
#define SFML_CLOCK_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <SFML/System/Time.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility class that measures the elapsed time
///
////////////////////////////////////////////////////////////
class SFML_SYSTEM_API Clock
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// The clock starts automatically after being constructed.
///
////////////////////////////////////////////////////////////
Clock();
////////////////////////////////////////////////////////////
/// \brief Get the elapsed time
///
/// This function returns the time elapsed since the last call
/// to restart() (or the construction of the instance if restart()
/// has not been called).
///
/// \return Time elapsed
///
////////////////////////////////////////////////////////////
Time getElapsedTime() const;
////////////////////////////////////////////////////////////
/// \brief Restart the clock
///
/// This function puts the time counter back to zero.
/// It also returns the time elapsed since the clock was started.
///
/// \return Time elapsed
///
////////////////////////////////////////////////////////////
Time restart();
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Time m_startTime; ///< Time of last reset, in microseconds
};
} // namespace sf
#endif // SFML_CLOCK_HPP
////////////////////////////////////////////////////////////
/// \class sf::Clock
/// \ingroup system
///
/// sf::Clock is a lightweight class for measuring time.
///
/// Its provides the most precise time that the underlying
/// OS can achieve (generally microseconds or nanoseconds).
/// It also ensures monotonicity, which means that the returned
/// time can never go backward, even if the system time is
/// changed.
///
/// Usage example:
/// \code
/// sf::Clock clock;
/// ...
/// Time time1 = clock.getElapsedTime();
/// ...
/// Time time2 = clock.restart();
/// \endcode
///
/// The sf::Time value returned by the clock can then be
/// converted to a number of seconds, milliseconds or even
/// microseconds.
///
/// \see sf::Time
///
////////////////////////////////////////////////////////////

View file

@ -1,80 +1,80 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_ERR_HPP
#define SFML_ERR_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <ostream>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Standard stream used by SFML to output warnings and errors
///
////////////////////////////////////////////////////////////
SFML_SYSTEM_API std::ostream& err();
} // namespace sf
#endif // SFML_ERR_HPP
////////////////////////////////////////////////////////////
/// \fn sf::err
/// \ingroup system
///
/// By default, sf::err() outputs to the same location as std::cerr,
/// (-> the stderr descriptor) which is the console if there's
/// one available.
///
/// It is a standard std::ostream instance, so it supports all the
/// insertion operations defined by the STL
/// (operator <<, manipulators, etc.).
///
/// sf::err() can be redirected to write to another output, independently
/// of std::cerr, by using the rdbuf() function provided by the
/// std::ostream class.
///
/// Example:
/// \code
/// // Redirect to a file
/// std::ofstream file("sfml-log.txt");
/// std::streambuf* previous = sf::err().rdbuf(file.rdbuf());
///
/// // Redirect to nothing
/// sf::err().rdbuf(NULL);
///
/// // Restore the original output
/// sf::err().rdbuf(previous);
/// \endcode
///
/// \return Reference to std::ostream representing the SFML error stream
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_ERR_HPP
#define SFML_ERR_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <ostream>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Standard stream used by SFML to output warnings and errors
///
////////////////////////////////////////////////////////////
SFML_SYSTEM_API std::ostream& err();
} // namespace sf
#endif // SFML_ERR_HPP
////////////////////////////////////////////////////////////
/// \fn sf::err
/// \ingroup system
///
/// By default, sf::err() outputs to the same location as std::cerr,
/// (-> the stderr descriptor) which is the console if there's
/// one available.
///
/// It is a standard std::ostream instance, so it supports all the
/// insertion operations defined by the STL
/// (operator <<, manipulators, etc.).
///
/// sf::err() can be redirected to write to another output, independently
/// of std::cerr, by using the rdbuf() function provided by the
/// std::ostream class.
///
/// Example:
/// \code
/// // Redirect to a file
/// std::ofstream file("sfml-log.txt");
/// std::streambuf* previous = sf::err().rdbuf(file.rdbuf());
///
/// // Redirect to nothing
/// sf::err().rdbuf(NULL);
///
/// // Restore the original output
/// sf::err().rdbuf(previous);
/// \endcode
///
/// \return Reference to std::ostream representing the SFML error stream
///
////////////////////////////////////////////////////////////

View file

@ -39,7 +39,7 @@ namespace sf
////////////////////////////////////////////////////////////
class InputStream
{
public :
public:
////////////////////////////////////////////////////////////
/// \brief Virtual destructor
@ -114,7 +114,7 @@ public :
/// // custom stream class that reads from inside a zip file
/// class ZipStream : public sf::InputStream
/// {
/// public :
/// public:
///
/// ZipStream(std::string archive);
///
@ -128,7 +128,7 @@ public :
///
/// Int64 getSize();
///
/// private :
/// private:
///
/// ...
/// };

View file

@ -1,139 +1,139 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_LOCK_HPP
#define SFML_LOCK_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <SFML/System/NonCopyable.hpp>
namespace sf
{
class Mutex;
////////////////////////////////////////////////////////////
/// \brief Automatic wrapper for locking and unlocking mutexes
///
////////////////////////////////////////////////////////////
class SFML_SYSTEM_API Lock : NonCopyable
{
public :
////////////////////////////////////////////////////////////
/// \brief Construct the lock with a target mutex
///
/// The mutex passed to sf::Lock is automatically locked.
///
/// \param mutex Mutex to lock
///
////////////////////////////////////////////////////////////
explicit Lock(Mutex& mutex);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// The destructor of sf::Lock automatically unlocks its mutex.
///
////////////////////////////////////////////////////////////
~Lock();
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Mutex& m_mutex; ///< Mutex to lock / unlock
};
} // namespace sf
#endif // SFML_LOCK_HPP
////////////////////////////////////////////////////////////
/// \class sf::Lock
/// \ingroup system
///
/// sf::Lock is a RAII wrapper for sf::Mutex. By unlocking
/// it in its destructor, it ensures that the mutex will
/// always be released when the current scope (most likely
/// a function) ends.
/// This is even more important when an exception or an early
/// return statement can interrupt the execution flow of the
/// function.
///
/// For maximum robustness, sf::Lock should always be used
/// to lock/unlock a mutex.
///
/// Usage example:
/// \code
/// sf::Mutex mutex;
///
/// void function()
/// {
/// sf::Lock lock(mutex); // mutex is now locked
///
/// functionThatMayThrowAnException(); // mutex is unlocked if this function throws
///
/// if (someCondition)
/// return; // mutex is unlocked
///
/// } // mutex is unlocked
/// \endcode
///
/// Because the mutex is not explicitely unlocked in the code,
/// it may remain locked longer than needed. If the region
/// of the code that needs to be protected by the mutex is
/// not the entire function, a good practice is to create a
/// smaller, inner scope so that the lock is limited to this
/// part of the code.
///
/// \code
/// sf::Mutex mutex;
///
/// void function()
/// {
/// {
/// sf::Lock lock(mutex);
/// codeThatRequiresProtection();
///
/// } // mutex is unlocked here
///
/// codeThatDoesntCareAboutTheMutex();
/// }
/// \endcode
///
/// Having a mutex locked longer than required is a bad practice
/// which can lead to bad performances. Don't forget that when
/// a mutex is locked, other threads may be waiting doing nothing
/// until it is released.
///
/// \see sf::Mutex
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_LOCK_HPP
#define SFML_LOCK_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <SFML/System/NonCopyable.hpp>
namespace sf
{
class Mutex;
////////////////////////////////////////////////////////////
/// \brief Automatic wrapper for locking and unlocking mutexes
///
////////////////////////////////////////////////////////////
class SFML_SYSTEM_API Lock : NonCopyable
{
public:
////////////////////////////////////////////////////////////
/// \brief Construct the lock with a target mutex
///
/// The mutex passed to sf::Lock is automatically locked.
///
/// \param mutex Mutex to lock
///
////////////////////////////////////////////////////////////
explicit Lock(Mutex& mutex);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// The destructor of sf::Lock automatically unlocks its mutex.
///
////////////////////////////////////////////////////////////
~Lock();
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Mutex& m_mutex; ///< Mutex to lock / unlock
};
} // namespace sf
#endif // SFML_LOCK_HPP
////////////////////////////////////////////////////////////
/// \class sf::Lock
/// \ingroup system
///
/// sf::Lock is a RAII wrapper for sf::Mutex. By unlocking
/// it in its destructor, it ensures that the mutex will
/// always be released when the current scope (most likely
/// a function) ends.
/// This is even more important when an exception or an early
/// return statement can interrupt the execution flow of the
/// function.
///
/// For maximum robustness, sf::Lock should always be used
/// to lock/unlock a mutex.
///
/// Usage example:
/// \code
/// sf::Mutex mutex;
///
/// void function()
/// {
/// sf::Lock lock(mutex); // mutex is now locked
///
/// functionThatMayThrowAnException(); // mutex is unlocked if this function throws
///
/// if (someCondition)
/// return; // mutex is unlocked
///
/// } // mutex is unlocked
/// \endcode
///
/// Because the mutex is not explicitely unlocked in the code,
/// it may remain locked longer than needed. If the region
/// of the code that needs to be protected by the mutex is
/// not the entire function, a good practice is to create a
/// smaller, inner scope so that the lock is limited to this
/// part of the code.
///
/// \code
/// sf::Mutex mutex;
///
/// void function()
/// {
/// {
/// sf::Lock lock(mutex);
/// codeThatRequiresProtection();
///
/// } // mutex is unlocked here
///
/// codeThatDoesntCareAboutTheMutex();
/// }
/// \endcode
///
/// Having a mutex locked longer than required is a bad practice
/// which can lead to bad performances. Don't forget that when
/// a mutex is locked, other threads may be waiting doing nothing
/// until it is released.
///
/// \see sf::Mutex
///
////////////////////////////////////////////////////////////

View file

@ -1,148 +1,148 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_MUTEX_HPP
#define SFML_MUTEX_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <SFML/System/NonCopyable.hpp>
namespace sf
{
namespace priv
{
class MutexImpl;
}
////////////////////////////////////////////////////////////
/// \brief Blocks concurrent access to shared resources
/// from multiple threads
///
////////////////////////////////////////////////////////////
class SFML_SYSTEM_API Mutex : NonCopyable
{
public :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Mutex();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~Mutex();
////////////////////////////////////////////////////////////
/// \brief Lock the mutex
///
/// If the mutex is already locked in another thread,
/// this call will block the execution until the mutex
/// is released.
///
/// \see unlock
///
////////////////////////////////////////////////////////////
void lock();
////////////////////////////////////////////////////////////
/// \brief Unlock the mutex
///
/// \see lock
///
////////////////////////////////////////////////////////////
void unlock();
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
priv::MutexImpl* m_mutexImpl; ///< OS-specific implementation
};
} // namespace sf
#endif // SFML_MUTEX_HPP
////////////////////////////////////////////////////////////
/// \class sf::Mutex
/// \ingroup system
///
/// Mutex stands for "MUTual EXclusion". A mutex is a
/// synchronization object, used when multiple threads are involved.
///
/// When you want to protect a part of the code from being accessed
/// simultaneously by multiple threads, you typically use a
/// mutex. When a thread is locked by a mutex, any other thread
/// trying to lock it will be blocked until the mutex is released
/// by the thread that locked it. This way, you can allow only
/// one thread at a time to access a critical region of your code.
///
/// Usage example:
/// \code
/// Database database; // this is a critical resource that needs some protection
/// sf::Mutex mutex;
///
/// void thread1()
/// {
/// mutex.lock(); // this call will block the thread if the mutex is already locked by thread2
/// database.write(...);
/// mutex.unlock(); // if thread2 was waiting, it will now be unblocked
/// }
///
/// void thread2()
/// {
/// mutex.lock(); // this call will block the thread if the mutex is already locked by thread1
/// database.write(...);
/// mutex.unlock(); // if thread1 was waiting, it will now be unblocked
/// }
/// \endcode
///
/// Be very careful with mutexes. A bad usage can lead to bad problems,
/// like deadlocks (two threads are waiting for each other and the
/// application is globally stuck).
///
/// To make the usage of mutexes more robust, particularly in
/// environments where exceptions can be thrown, you should
/// use the helper class sf::Lock to lock/unlock mutexes.
///
/// SFML mutexes are recursive, which means that you can lock
/// a mutex multiple times in the same thread without creating
/// a deadlock. In this case, the first call to lock() behaves
/// as usual, and the following ones have no effect.
/// However, you must call unlock() exactly as many times as you
/// called lock(). If you don't, the mutex won't be released.
///
/// \see sf::Lock
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_MUTEX_HPP
#define SFML_MUTEX_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <SFML/System/NonCopyable.hpp>
namespace sf
{
namespace priv
{
class MutexImpl;
}
////////////////////////////////////////////////////////////
/// \brief Blocks concurrent access to shared resources
/// from multiple threads
///
////////////////////////////////////////////////////////////
class SFML_SYSTEM_API Mutex : NonCopyable
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Mutex();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~Mutex();
////////////////////////////////////////////////////////////
/// \brief Lock the mutex
///
/// If the mutex is already locked in another thread,
/// this call will block the execution until the mutex
/// is released.
///
/// \see unlock
///
////////////////////////////////////////////////////////////
void lock();
////////////////////////////////////////////////////////////
/// \brief Unlock the mutex
///
/// \see lock
///
////////////////////////////////////////////////////////////
void unlock();
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
priv::MutexImpl* m_mutexImpl; ///< OS-specific implementation
};
} // namespace sf
#endif // SFML_MUTEX_HPP
////////////////////////////////////////////////////////////
/// \class sf::Mutex
/// \ingroup system
///
/// Mutex stands for "MUTual EXclusion". A mutex is a
/// synchronization object, used when multiple threads are involved.
///
/// When you want to protect a part of the code from being accessed
/// simultaneously by multiple threads, you typically use a
/// mutex. When a thread is locked by a mutex, any other thread
/// trying to lock it will be blocked until the mutex is released
/// by the thread that locked it. This way, you can allow only
/// one thread at a time to access a critical region of your code.
///
/// Usage example:
/// \code
/// Database database; // this is a critical resource that needs some protection
/// sf::Mutex mutex;
///
/// void thread1()
/// {
/// mutex.lock(); // this call will block the thread if the mutex is already locked by thread2
/// database.write(...);
/// mutex.unlock(); // if thread2 was waiting, it will now be unblocked
/// }
///
/// void thread2()
/// {
/// mutex.lock(); // this call will block the thread if the mutex is already locked by thread1
/// database.write(...);
/// mutex.unlock(); // if thread1 was waiting, it will now be unblocked
/// }
/// \endcode
///
/// Be very careful with mutexes. A bad usage can lead to bad problems,
/// like deadlocks (two threads are waiting for each other and the
/// application is globally stuck).
///
/// To make the usage of mutexes more robust, particularly in
/// environments where exceptions can be thrown, you should
/// use the helper class sf::Lock to lock/unlock mutexes.
///
/// SFML mutexes are recursive, which means that you can lock
/// a mutex multiple times in the same thread without creating
/// a deadlock. In this case, the first call to lock() behaves
/// as usual, and the following ones have no effect.
/// However, you must call unlock() exactly as many times as you
/// called lock(). If you don't, the mutex won't be released.
///
/// \see sf::Lock
///
////////////////////////////////////////////////////////////

View file

@ -1,119 +1,119 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_NONCOPYABLE_HPP
#define SFML_NONCOPYABLE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility class that makes any derived
/// class non-copyable
///
////////////////////////////////////////////////////////////
class SFML_SYSTEM_API NonCopyable
{
protected :
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Because this class has a copy constructor, the compiler
/// will not automatically generate the default constructor.
/// That's why we must define it explicitely.
///
////////////////////////////////////////////////////////////
NonCopyable() {}
private :
////////////////////////////////////////////////////////////
/// \brief Disabled copy constructor
///
/// By making the copy constructor private, the compiler will
/// trigger an error if anyone outside tries to use it.
/// To prevent NonCopyable or friend classes from using it,
/// we also give no definition, so that the linker will
/// produce an error if the first protection was inefficient.
///
////////////////////////////////////////////////////////////
NonCopyable(const NonCopyable&);
////////////////////////////////////////////////////////////
/// \brief Disabled assignment operator
///
/// By making the assignment operator private, the compiler will
/// trigger an error if anyone outside tries to use it.
/// To prevent NonCopyable or friend classes from using it,
/// we also give no definition, so that the linker will
/// produce an error if the first protection was inefficient.
///
////////////////////////////////////////////////////////////
NonCopyable& operator =(const NonCopyable&);
};
} // namespace sf
#endif // SFML_NONCOPYABLE_HPP
////////////////////////////////////////////////////////////
/// \class sf::NonCopyable
/// \ingroup system
///
/// This class makes its instances non-copyable, by explicitely
/// disabling its copy constructor and its assignment operator.
///
/// To create a non-copyable class, simply inherit from
/// sf::NonCopyable.
///
/// The type of inheritance (public or private) doesn't matter,
/// the copy constructor and assignment operator are declared private
/// in sf::NonCopyable so they will end up being inaccessible in both
/// cases. Thus you can use a shorter syntax for inheriting from it
/// (see below).
///
/// Usage example:
/// \code
/// class MyNonCopyableClass : sf::NonCopyable
/// {
/// ...
/// };
/// \endcode
///
/// Deciding whether the instances of a class can be copied
/// or not is a very important design choice. You are strongly
/// encouraged to think about it before writing a class,
/// and to use sf::NonCopyable when necessary to prevent
/// many potential future errors when using it. This is also
/// a very important indication to users of your class.
///
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_NONCOPYABLE_HPP
#define SFML_NONCOPYABLE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility class that makes any derived
/// class non-copyable
///
////////////////////////////////////////////////////////////
class SFML_SYSTEM_API NonCopyable
{
protected:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Because this class has a copy constructor, the compiler
/// will not automatically generate the default constructor.
/// That's why we must define it explicitely.
///
////////////////////////////////////////////////////////////
NonCopyable() {}
private:
////////////////////////////////////////////////////////////
/// \brief Disabled copy constructor
///
/// By making the copy constructor private, the compiler will
/// trigger an error if anyone outside tries to use it.
/// To prevent NonCopyable or friend classes from using it,
/// we also give no definition, so that the linker will
/// produce an error if the first protection was inefficient.
///
////////////////////////////////////////////////////////////
NonCopyable(const NonCopyable&);
////////////////////////////////////////////////////////////
/// \brief Disabled assignment operator
///
/// By making the assignment operator private, the compiler will
/// trigger an error if anyone outside tries to use it.
/// To prevent NonCopyable or friend classes from using it,
/// we also give no definition, so that the linker will
/// produce an error if the first protection was inefficient.
///
////////////////////////////////////////////////////////////
NonCopyable& operator =(const NonCopyable&);
};
} // namespace sf
#endif // SFML_NONCOPYABLE_HPP
////////////////////////////////////////////////////////////
/// \class sf::NonCopyable
/// \ingroup system
///
/// This class makes its instances non-copyable, by explicitely
/// disabling its copy constructor and its assignment operator.
///
/// To create a non-copyable class, simply inherit from
/// sf::NonCopyable.
///
/// The type of inheritance (public or private) doesn't matter,
/// the copy constructor and assignment operator are declared private
/// in sf::NonCopyable so they will end up being inaccessible in both
/// cases. Thus you can use a shorter syntax for inheriting from it
/// (see below).
///
/// Usage example:
/// \code
/// class MyNonCopyableClass : sf::NonCopyable
/// {
/// ...
/// };
/// \endcode
///
/// Deciding whether the instances of a class can be copied
/// or not is a very important design choice. You are strongly
/// encouraged to think about it before writing a class,
/// and to use sf::NonCopyable when necessary to prevent
/// many potential future errors when using it. This is also
/// a very important indication to users of your class.
///
////////////////////////////////////////////////////////////

View file

@ -1,52 +1,52 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SLEEP_HPP
#define SFML_SLEEP_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <SFML/System/Time.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \ingroup system
/// \brief Make the current thread sleep for a given duration
///
/// sf::sleep is the best way to block a program or one of its
/// threads, as it doesn't consume any CPU power.
///
/// \param duration Time to sleep
///
////////////////////////////////////////////////////////////
void SFML_SYSTEM_API sleep(Time duration);
} // namespace sf
#endif // SFML_SLEEP_HPP
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SLEEP_HPP
#define SFML_SLEEP_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Export.hpp>
#include <SFML/System/Time.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \ingroup system
/// \brief Make the current thread sleep for a given duration
///
/// sf::sleep is the best way to block a program or one of its
/// threads, as it doesn't consume any CPU power.
///
/// \param duration Time to sleep
///
////////////////////////////////////////////////////////////
void SFML_SYSTEM_API sleep(Time duration);
} // namespace sf
#endif // SFML_SLEEP_HPP

Some files were not shown because too many files have changed in this diff Show more